2017-09-03 44 views
1

所以我到处搜索,我不能为我的爱找出什么是错的!我正在研究一个需要博客文章和slu web的web应用程序直接与文章的名称(包括一些正则表达式)相关联。但是,当更新发布一切变化除了slu!!所以url参数仍然显示旧的slu instead,而不是新的。有什么想法吗?更新slu。.pre('保存')

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 
    } 
}) 
+1

你错过了一个重要的细节。你如何更新?用示例代码编辑您的问题。在'pre'中间件中添加'console.log()'语句,看看它在更新时是否被调用。 – Mikey

回答

0

当使用猫鼬更新方法,例如Model.findByIdAndUpdate(),预保存钩未烧制。

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

例如:

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