Search code examples
mongodbmongoosemongoose-schema

Mongoose pre save hook is triggering while updating via Model.save()


I am saving a smaller unique id for mongodb documents via pre hook.

schema.pre('save', function(next) {
    this.refId = uid();
    next();
});

As far as I understand save hook only runs when a document is created.

But when I get the document via query and try to save it by adding some new data the unique id (refId) field gets updated as well.

const foo = Foo.findOne({refId: 'fwe23fw23'});

Foo.field = 'new value';
Foo.save(); // runs pre hook again;

That leads me to believe save hook runs on every save() query wheather or not its a create or update method.

How do I make sure the refId only created once and never changes on any update operation?

NOTE: I understand I can use updateOne() on the Model itself to update the document. But I want to understand why saving the document itself doesn't work.


Solution

  • Both document.save() and Model.create triggers pre save hook.

    You can use isNew property to check if the document is created.

    schema.pre("save", function(next) {
      if (this.isNew) {
        this.refId = uid();
      }
    
      next();
    });
    

    Now refId will be only created only one time when the document is created, and it's value will not change when save used.