Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I tried findByIdAndUpdate markdown I can't update it. can you guide me

I built to create sanitizedHtml with post
But I can’t update it. What should I do?

When I try to update the description part updates but the sanitizedHtml does not update.

And I tried many ways, I think it might be a problem with findByIdAndUpdate.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

or the problem comes from sanitizedHtml

models:

    const mongoose = require('mongoose');
const marked = require('marked');
const html = marked.parse('# Marked in Node.js\n\nRendered by **marked**.');
const createDomPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const dompurify = createDomPurify(new JSDOM().window);
const Schema = mongoose.Schema;
const Reviewofdharma = require('../models/reviewofdharma');


const ImageSchema = new Schema({
    url: String,
    filename: String
});

ImageSchema.virtual('thumbnail').get(function() {
    return this.url.replace('/upload', '/upload/w_200');
});

const opts = { toJSON: { virtuals: true } }

const DharmaSchema = new Schema({
    title: {
        type: String,
        required: true        
    },
    images: [ImageSchema],
    // geometry: {
    //     type: {
    //       type: String,
    //       enum: ['Point'],          
    //       required: true
    //     },
    //     coordinates: {
    //       type: [Number],
    //       required: true
    //     }
    // },
    price: String,
    description: {
        type: String,
        required: true
    },
    location: String,
    sanitizedHtml: {
        type: String,
        required: true,        
    },
    sanitizedHtml: marked(values.body),
    // createdAt: { type: Date, default: Date.now },
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    reviewofdharmas: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Reviewofdharma'
        }
    ]
    },
    {
        timestamps: true
    },
    
opts )

DharmaSchema.virtual('properties.popUpMarkup').get(function() {
    return `
    <strong><a href="/dharmas/${this._id}">${this.title}</a><strong>
    <p>${this.description.substring(0, 50)}...</p>`
});

DharmaSchema.post('findOneAndDelete', async function(doc){
    if(doc){
        await Reviewofdharma.deleteMany({
            _id: {
                $in: doc.reviewofdharmas
            }
        })
    }
})

DharmaSchema.pre('validate', function(next) {
    if (this.description) {
        this.sanitizedHtml = dompurify.sanitize(marked.parse(this.description))
    }
    next()
})


module.exports = mongoose.model('Dharma', DharmaSchema);

routes:

const express = require('express');
const router = express.Router();
const dharmas = require('../controllers/dharmas')
const catchAsync = require('../utils/catchAsync');
const { isLoggedIn2, validateDharma 
} = require('../middleware');
const multer = require('multer')
const { storage } = require('../cloudinary/dharma');
const upload = multer({ storage })

const ExpressError = require('../utils/ExpressError');
const Dharma = require('../models/dharma');

router.route('/')
    .get(catchAsync(dharmas.index))
    .post(
        isLoggedIn2, 
        upload.array('image'), 
        validateDharma, 
        catchAsync(dharmas.createDharma))
    // .post((dharmas.createDharma2))

router.get('/new', isLoggedIn2, dharmas.renderNewForm)

router.route('/:id')
    .get(catchAsync(dharmas.showDharma))
    .put(isLoggedIn2, upload.array('image'), validateDharma, catchAsync(dharmas.updateDharma))
    .delete(isLoggedIn2, catchAsync(dharmas.deleteDharma))

router.get('/:id/edit', isLoggedIn2, catchAsync(dharmas.renderEditForm))



module.exports = router;

controllers:

const Dharma = require('../models/dharma');
// const mbxGeocoding = require('@mapbox/mapbox-sdk/services/geocoding');
const mapBoxToken = process.env.MAPBOX_TOKEN;
// const geocoder = mbxGeocoding({ accessToken: mapBoxToken });
const { cloudinary } = require('../cloudinary/dharma');


module.exports.index = async (req, res) => {
    const dharmas = await Dharma.find({}).sort({
        createdAt: 'desc'
    })
    res.render('dharmas/homeV2', { dharmas })
}

module.exports.renderNewForm = (req, res) => {
    res.render('dharmas/new');
}

module.exports.createDharma = async(req, res, next) => {
    // const geoData = await geocoder.forwardGeocode({
    //     query: req.body.dharma.location,
    //     limit: 1
    // }).send()
    const dharma = new Dharma(req.body.dharma);
    // dharma.geometry = geoData.body.features[0].geometry;
    dharma.images = req.files.map(f => ({ url: f.path, filename: f.filename }));
    dharma.author = req.user._id;
    await dharma.save();
    console.log(dharma);
    req.flash('infoDharma', 'โพสต์สำเร็จ');
    res.redirect(`${dharma._id}`)
}

// module.exports.createDharma2 = async (req, res) => {
//     const dharma = new Dharma({
//         title: req.body.title,
//         description: req.body.description
//     })
//     try {
//         dharma = await dharma.save()
//         res.redirect(`${dharma.id}`)
//     } catch (e) {
//         res.render(`${dharma.id}`, { dharma })
//     }
// }

module.exports.showDharma = async (req, res) => {
    const dharma = await Dharma.findById(req.params.id).populate('reviewofdharmas').populate('author');
    if(!dharma){
        req.flash('error', 'ไม่พบข้อมูล');
        return res.redirect('/dharmas');
    }
    console.log(dharma);
    res.render('dharmas/show', { dharma });
}

module.exports.renderEditForm = async (req, res) => {
    const dharma = await Dharma.findById(req.params.id)
    if(!dharma){
        req.flash('error', 'ไม่พบข้อมูล');
        return res.redirect('/dharmas');
    }
    res.render('dharmas/edit', { dharma });
}

module.exports.updateDharma = async (req, res) => {
    const { id } = req.params;
    console.log(req.body);
    const dharma = await Dharma.findByIdAndUpdate(id, { ...req.body.dharma });
    const imgs = req.files.map(f => ({ url: f.path, filename: f.filename }));
    dharma.images.push(...imgs);
    await dharma.save()
    if(req.body.deleteImages){
        for(let filename of req.body.deleteImages){
            await cloudinary.uploader.destroy(filename);
        }
        await dharma.updateOne({ $pull: { images: {filename: { $in: req.body.deleteImages } } } } )
    }
    req.flash('infoDharma', 'อัปเดตสำเร็จ');
    res.redirect(`${dharma._id}`)
}

module.exports.deleteDharma = async (req, res) => {
    const { id } = req.params;
    await Dharma.findByIdAndDelete(id);
    req.flash('infoDharma', 'ลบโพสต์สำเร็จ');
    res.redirect('/');
}

>Solution :

You should add the { new: true } flag to return the updated object:

const dharma = await Dharma.findByIdAndUpdate(
    id,
    { ...req.body.dharma },
    { new: true }
  );

With that you should be able to run the following dharma.images.push(...imgs) statement.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading