Determine whether doc is new or exists in mongoose Post middleware’s ‘save’?

@aheckmann reply at github

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

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

isNew is an key used by mongoose internally. Saving that value to the document’s wasNew in the pre save hook allows the post save hook to know whether this was an existing document or a newly created one. Additionally, the wasNew is not commited to the document unless you specifically add it to the schema.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)