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
}
})
あなたは重要なディテールを逃しました。どのように更新しますか?サンプルコードで質問を編集します。あなたの 'pre'ミドルウェアに' console.log() 'ステートメントを追加し、更新時に呼び出されるかどうかを確認してください。 – Mikey