【问题标题】:Determine whether doc is new or exists in mongoose Post middleware's 'save'?确定 doc 是新的还是存在于 mongoose Post 中间件的“保存”中?
【发布时间】:2013-06-10 13:03:55
【问题描述】:

来自Mongoose JS 文档:

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

有没有办法确定这是原始保存还是现有文档的保存(更新)?

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    @aheckmann reply at github

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

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

    【讨论】:

    • @jysperm 你的评论让我很困惑,因为这个例子同时使用了wasNewisNew...所以改变了什么?
    • isNew 在进入 Schema.post('save') 中间件之前发生了什么变化?
    【解决方案2】:

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

    【讨论】:

    • Mongoose 以其出色的文档而闻名。
    【解决方案3】:
    schema.post('save')
    

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

    schema.post('save', function () {
        console.log('New object has been created.');
    });
    

    【讨论】:

    • 这根本不是真的,这个答案应该去掉
    猜你喜欢
    • 2015-01-14
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多