2017-09-03 5 views
1

私はどこでも洗ったので、私の愛のために何が間違っているのか理解できません!私はブログの投稿を必要とするウェブアプリケーションに取り組んでいて、スラッグは記事の名前(正規表現を含む)に直接結びついています。しかし、ポストを更新すると、スラッグのほかにすべてが変わります!だから、urlのparamsはまだ新しいものの代わりに古いスラッグを表示します。何かご意見は? mongoose .pre( 'save')を使ってスラッグを更新する

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) { 
     // ... 
    }); 
}); 
関連する問題