用m Updating更新slu。.pre('save')

所以我到处跑,我不能为了我的爱找出什么是错的! 我工作的Web应用程序需要博客文章和slu is直接绑定到文章的名称(包括一些正则expression式)。 但是,当更新发布除slug之外的一切变化! 所以url参数仍然显示旧的slu instead,而不是新的。 有什么想法吗?

const articleSchema = new mongoose.Schema({ name:{ type: String, trim: true, required: 'Please enter an article name' }, slug: String, description:{ type: String, trim: true, required: 'Please enter an description' }, content:{ type: String, trim: true, required: 'Please enter article content' }, tags: [String], created:{ type: Date, default: Date.now }, photo: String }) articleSchema.pre('save', async function(next){ try{ if(!this.isModified('name')){ next() return; } this.slug = slug(this.name) const slugRegEx = new RegExp(`^(${this.slug})((-[0-9]*$)?)$`,'i') const articlesWithSlug = await this.constructor.find({slug: slugRegEx}) if(articlesWithSlug.length){ this.slug = `${this.slug}-${articlesWithSlug.length + 1}` } next() }catch(error){ throw error } }) 

在Mongoose中使用更新方法(如Model.findByIdAndUpdate())时 ,不会触发预保存钩子。

如果您需要启动预存储钩子,则必须调用save方法。

例如:

 MyModel.findById(id, function(err, doc) { doc.name = 'new name'; doc.save(function(err, doc) { // ... }); });