Determine if a record "is new" in the pre save callback


Question

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?

1
47
8/23/2012 1:31:49 PM

Accepted Answer

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

87
6/23/2015 6:30:36 PM

var MySchema = new Schema({...});

MySchema.pre('save', function(next) {
    if (this.isNew) {
        // Hooray !
    }
    next();
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon