Skip to content Skip to sidebar Skip to footer

Insert Document Only If Not Already Exists

I am creating documents with Subscription.create({ email: req.body.email }, (err, subscription) => { // }); I have made the email field unique in my Mongoose schema, so it's

Solution 1:

In mongoose you can use the pre function.

var schema = new Schema(..);
schema.pre('save', function(next) {
  // Check if the mail exists. If it does, just throw an exception// If not, just create the thing using next.
  next();
});

You should be careful to catch the exception and when you call the save function. I believe this will do the work.

Post a Comment for "Insert Document Only If Not Already Exists"