我试过 findByIdAndUpdate markdown 我无法更新它。你能指导我吗
I tried findByIdAndUpdate markdown I can't update it. can you guide me
我用 post 创建了 sanitizedHtml
但我无法更新它。我该怎么办?
当我尝试更新描述部分时更新但 sanitizedHtml 没有更新。
而且试了很多方法,我觉得可能是findByIdAndUpdate的问题。
或者问题来自 sanitizedHtml
型号:
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);
路线:
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;
控制器:
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('/');
}
您应该将 { new: true }
标志添加到 return 更新的对象:
const dharma = await Dharma.findByIdAndUpdate(
id,
{ ...req.body.dharma },
{ new: true }
);
有了它,您应该能够 运行 以下 dharma.images.push(...imgs)
语句。
我用 post 创建了 sanitizedHtml 但我无法更新它。我该怎么办?
当我尝试更新描述部分时更新但 sanitizedHtml 没有更新。
而且试了很多方法,我觉得可能是findByIdAndUpdate的问题。
或者问题来自 sanitizedHtml
型号:
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);
路线:
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;
控制器:
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('/');
}
您应该将 { new: true }
标志添加到 return 更新的对象:
const dharma = await Dharma.findByIdAndUpdate(
id,
{ ...req.body.dharma },
{ new: true }
);
有了它,您应该能够 运行 以下 dharma.images.push(...imgs)
语句。