1

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();
});
Saeed Ahadian
  • 212
  • 2
  • 4
  • 14

1 Answers1

0

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.

Vaasu Dhand
  • 499
  • 1
  • 8
  • 14