当 Mongoose 中的预保存挂钩失败时,如何静默跳过保存文档?

问题描述

我正在向数据库添加一系列文档。这些文档中的每一个都在预保存挂钩中进行验证。我希望 Mongoose 忽略保存未通过验证的特定文档而不抛出任何错误,以便可以保存通过验证的其余文档。这是一个示例代码

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

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

  next();
});

解决方法

我们可以在save pre-hook中使用Mongoose的inNew方法。这是一个对我有用的解决方案:

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!`);
  }
})

注意:此代码应在您的模型文件中。