【发布时间】: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.0 和 Mongoose custom validation for password 都没有帮助。
如何验证电子邮件地址的唯一性并避免该错误?
【问题讨论】: