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

node.jsMongodbMongoose

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsilverfighterView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow
Solution 2 - node.jsmartynasView Answer on Stackoverflow