【问题标题】:Mongoose: the isAsync option for custom validators is deprecatedMongoose:自定义验证器的 isAsync 选项已弃用
【发布时间】:2021-02-09 00:21:52
【问题描述】:

Stripe Rocket Rides demo 在验证器中使用 isAsync

// Make sure the email has not been used.
PilotSchema.path('email').validate({
  isAsync: true,
  validator: function(email, callback) {
    const Pilot = mongoose.model('Pilot');
    // Check only when it is a new pilot or when the email has been modified.
    if (this.isNew || this.isModified('email')) {
      Pilot.find({ email: email }).exec(function(err, pilots) {
        callback(!err && pilots.length === 0);
      });
    } else {
      callback(true);
    }
  },
  message: 'This email already exists. Please try to log in instead.',
});

此方法使用引用引发错误

弃用警告:猫鼬:自定义验证器的 `isAsync` 选项已弃用。让您的异步验证器返回一个承诺:https://mongoosejs.com/docs/validation.html#async-custom-validators

引用的 MongoDB 页面有这个代码:

const userSchema = new Schema({
  name: {
    type: String,
    // You can also make a validator async by returning a promise.
    validate: () => Promise.reject(new Error('Oops!'))
  },
  email: {
    type: String,
    // There are two ways for an promise-based async validator to fail:
    // 1) If the promise rejects, Mongoose assumes the validator failed with the given error.
    // 2) If the promise resolves to `false`, Mongoose assumes the validator failed and creates an error with the given `message`.
    validate: {
      validator: () => Promise.resolve(false),
      message: 'Email validation failed'
    }
  }
});

我是 NodeJS 的新手,我不知道如何将 MongoDB 代码调整到 Rocket Rides 演示。 Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0Mongoose custom validation for password 都没有帮助。

如何验证电子邮件地址的唯一性并避免该错误?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试这个,我遇到了同样的问题。

    修复它,请使用您通过 await 调用的单独的异步函数

    // Make sure the email has not been used.
    PilotSchema.path('email').validate({
        validator: async function(v) {
            return await checkMailDup(v, this);
        },
        message: 'This email already exists. Please try to log in instead.',
    });
    
    async function checkMailDup(v, t) {
      const Pilot = mongoose.model('Pilot');
      // Check only when it is a new pilot or when the email has been modified.
      if (t.isNew || t.isModified('email')) {
          try {
            const pilots = await Pilot.find({ email: v });
            return pilots.length === 0;
          } catch (err) {
            return false;
          }
      } else {
          return true;
      }
    }
    
    

    让我知道它是否有效

    我使用了以下参考资料:

    干杯!

    【讨论】:

    • 试试 checkMailDup 函数的新更新。问候!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 2017-09-10
    • 2021-04-25
    • 2018-06-11
    • 2014-04-06
    • 2014-05-29
    相关资源
    最近更新 更多