Determine if a record “is new” in the pre save callback

前端 未结 2 2031
逝去的感伤
逝去的感伤 2021-02-03 17:00

Is there a way to find out if a record \"is new\" (has not been save yet) in the pre save callback of mongoose model schema?

相关标签:
2条回答
  • 2021-02-03 17:44
    var MySchema = new Schema({...});
    
    MySchema.pre('save', function(next) {
        if (this.isNew) {
            // Hooray !
        }
        next();
    });
    
    0 讨论(0)
  • 2021-02-03 18:00

    Yes, there's an isNew boolean property on a model instance that indicates that. Access it as this.isNew from your pre save middleware.

    0 讨论(0)
提交回复
热议问题