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)?
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)?
schema.pre('save', function (next) {
this.wasNew = this.isNew;
next();
});
schema.post('save', function () {
if (this.wasNew) {
// ...
}
});
isNew
是 mongoose 内部使用的密钥。将该值保存到wasNew
pre save 钩子中的文档允许 post save 钩子知道这是现有文档还是新创建的文档。此外,wasNew
除非您专门将其添加到架构中,否则不会将其提交到文档中。
编辑:有关Document#isNew的信息,请参见 Document#isNew
schema.post('save')
不再识别更新事件。因此,不妨执行以下操作:
schema.post('save', function () {
console.log('New object has been created.');
});