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);
}
});
The pre-save hook is not the correct way to avoid duplicates. You should use findOneAndUpdate.
Your problem can be:
apiProductId and you are checking for a null value.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With