【问题标题】:Determine if a record "is new" in the pre save callback在预保存回调中确定记录是否“新”
【发布时间】:2023-03-27 23:35:01
【问题描述】:

有没有办法在猫鼬模型模式的预保存回调中找出记录是否“是新的”(尚未保存)?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    是的,模型实例上有一个 isNew 布尔属性表明了这一点。从您的预保存中间件以this.isNew 的身份访问它。

    【讨论】:

    • pre('update' 是否有类似的指标。我使用UserModel.update(filter, newUser, {upsert:true, new:true}, (err, user) ->,想知道它是新文档还是修改了现有文档。
    【解决方案2】:
    var MySchema = new Schema({...});
    
    MySchema.pre('save', function(next) {
        if (this.isNew) {
            // Hooray !
        }
        next();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2011-09-25
      • 2012-10-09
      相关资源
      最近更新 更多