How to silently skip saving a document when pre-save hook fails in Mongoose?

927 Views Asked by At

I'm adding a series of documents to the database. Each of these documents is validated in a pre-save hook. I want Mongoose to ignore saving that particular document that fails the validation without throwing any error so that the rest of the documents that pass the validation could be saved. Here is a sample code:

schema.pre('save', function (next) {
  // Validate something.
  const isValidated = ...;

  if (!isValidated) {
    // Skip saving document silently!
  }

  next();
});
1

There are 1 best solutions below

0
Vaasu Dhand On

We can use Mongoose's inNew method in the save pre-hook. Here's a solution that works for me:

model.ts

// Middleware that runs before saving images to DB
schema.pre('save', function (this: Image, next) {
  if (this.isNew) {
    next()
  } else {
    console.log(`Image ID - ${this._id} already exists!`);
  }
})

NOTE: This code should be in your model file.