我正在创建一个博客。这是我的Post
模型:
const postSchema = new mongoose.Schema({
title: String,
slug: String,
content: String
});
在保存帖子之前,我使用以下方法创建一个子弹:
postSchema.pre('save', async function(next) {
if(!this.isModified('title')) {
next();
return;
}
this.slug = slug(this.title);
const slugRegEx = new RegExp(`^(${this.slug})((-[0-9]*$)?)$`, 'i');
const postsWithSlug = await this.constructor.find({ slug: slugRegEx });
if (postsWithSlug.length) {
this.slug = `${this.slug}-${postsWithSlug.length + 1}`;
}
next();
});
如果以后要编辑帖子,请向/edit/:slug
发送POST请求:
router.post('/edit/:slug', async (req, res) => {
const post = await Post.findOneAndUpdate({ slug: req.params.slug }, req.body, {new: true, runValidators: true}).exec();
res.redirect(`/`);
});
编辑帖子后,如何更新子弹(如果需要更新)? save
方法不会调用findOneAndUpdate
方法吗?
感谢您的帮助!