Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose always inserting the first document and skipping the pre save hook

The code checks if a document exists in the DB (using pre save hook) and inserts it if it doesn't exist. It works fine, but not for the first document. It is always inserted. It seems that this first document doesn't trigger the pre save hook.

Model = require('./model')
var model = new Model();

//Before saving, check if the product exists
Model.schema.pre('save', function (next) {
    var self = this;
    Model.findOne({apiProductId: self.apiProductId}, function (err, product) {
        if (!product) {
            next();
        }
        else {
            next(new Error("Product exists: " + self.apiProductId));
        }
    });
 });

model.save(function (err, document) {
    if (err) {
        console.log(err);
    }
        else {
            console.log('Inserted: ' + document.apiProductId);
        }
});
like image 962
Lu Ju Avatar asked Jan 22 '26 19:01

Lu Ju


1 Answers

The pre-save hook is not the correct way to avoid duplicates. You should use findOneAndUpdate.

Your problem can be:

  1. You are trying to saving multiple documents asynchronously: the hook execution order is not predictable
  2. You have created a sparse index on apiProductId and you are checking for a null value.
like image 121
DBellavista Avatar answered Jan 24 '26 07:01

DBellavista