2017-01-16 3 views
0

マングースポストアップデートミドルウェアフック中に更新されたドキュメントにアクセスするための信頼できる/再利用可能な方法があるかどうかは疑問です。アクセスできるようです:mongoose更新ミドルウェアの更新中に更新されたドキュメントにアクセスするには?

schema.post('update', function (result) { 
    console.log(this) // Mongoose Query, no relevant doc info 
    console.log(result) // Mongoose CommandResult, no relevant doc info 
}) 

ありがとうございました!

+0

( '更新'、...)' 'schema.post( 'findOneAndUpdate'、関数(結果)試す{にconsole.log(結果);} ); '代わりに、変更されたドキュメントにアクセスします。 – chridam

答えて

-2

Schema.post('update')は(カスタムエラーメッセージを)エラー処理にのみ使用されている

// The same E11000 error can occur when you call `update()` 
// This function **must** take 3 parameters. If you use the 
// `passRawResult` function, this function **must** take 4 
// parameters 
Schema.post('update', function(error, res, next) { 
    if (error.name === 'MongoError' && error.code === 11000) { 
    next(new Error('There was a duplicate key error')); 
    } else { 
    next(error); 
    } 
}); 

あなたは、たとえば、すべての更新()の呼び出しにupdatedAtタイムスタンプを追加したい場合は、次の事前フックを使用します。代わり `schema.postの

Schema.pre('update', function() { 
    this.update({},{ $set: { updatedAt: new Date() } }); 
}); 

Read official docs

+0

downvoteに関するコメントはありますか? –

関連する問題