【发布时间】:2013-06-10 13:03:55
【问题描述】:
来自Mongoose JS 文档:
schema.post('save', function (doc) {
console.log('%s has been saved', doc._id);
})
有没有办法确定这是原始保存还是现有文档的保存(更新)?
【问题讨论】:
标签: mongoose
来自Mongoose JS 文档:
schema.post('save', function (doc) {
console.log('%s has been saved', doc._id);
})
有没有办法确定这是原始保存还是现有文档的保存(更新)?
【问题讨论】:
标签: mongoose
schema.pre('save', function (next) {
this.wasNew = this.isNew;
next();
});
schema.post('save', function () {
if (this.wasNew) {
// ...
}
});
isNew 是 mongoose 内部使用的密钥。在预保存挂钩中将该值保存到文档的wasNew 允许后保存挂钩知道这是现有文档还是新创建的文档。此外,wasNew 不会提交到文档中,除非您专门将其添加到架构中。
【讨论】:
wasNew 和isNew...所以改变了什么?
isNew 在进入 Schema.post('save') 中间件之前发生了什么变化?
编辑:有关 Document#isNew 的信息,请参阅 Document#isNew
【讨论】:
schema.post('save')
不再识别更新事件。因此,不妨执行以下操作:
schema.post('save', function () {
console.log('New object has been created.');
});
【讨论】: