34

From Mongoose JS documentation:

schema.post('save', function (doc) {
  console.log('%s has been saved', doc._id);
})

Is there any way to determine whether this is the original save or the saving of an existing document (an update)?

4

3 回答 3

98

@aheckmann 在 github 上回复

schema.pre('save', function (next) {
    this.wasNew = this.isNew;
    next();
});

schema.post('save', function () {
    if (this.wasNew) {
        // ...
    }
});

isNew是 mongoose 内部使用的密钥。将该值保存到wasNewpre save 钩子中的文档允许 post save 钩子知道这是现有文档还是新创建的文档。此外,wasNew除非您专门将其添加到架构中,否则不会将其提交到文档中。

于 2013-08-19T03:15:58.020 回答
6

编辑:有关Document#isNew的信息,请参见 Document#isNew

于 2013-06-14T00:18:54.920 回答
-11
schema.post('save')

不再识别更新事件。因此,不妨执行以下操作:

schema.post('save', function () {
    console.log('New object has been created.');
});
于 2015-10-01T04:54:04.970 回答