回调不起作用


const bookSchema = new mongoose.Schema({
name: { //for strings we havevaidators like
type: String,
required: true,
minlength: 5,
maxlength: 255,
},
auther_name: String,
tags: {
type: Array,
validate: {
// isAsync: true,
validator:async function (v, callBack) {
setTimeout(() => {
const result = v && v.length > 0;
callBack(result);
}, 1000);
},
message: 'A Document Should have at-least one tag'
}
},
date: {
type: Date, default: Date.now
},
isPublished: Boolean,
price: {
type: Number,
required: true,
min: 10,
max: 1000
}
});

请不要在验证器中使用setTimeout。因为您只想立即验证值,而不想使用回调。因为您只在验证器中返回true或false。

const bookSchema = new mongoose.Schema({
name: { //for strings we havevaidators like 
type: String, required: true, minlength: 5, maxlength: 255,
},
auther_name: String,
tags: {
type: Array,
validate: {
// isAsync: true,
validator: function (v) {
return  v?.length > 0;
},
message: 'A Document Should have at-least one tag'
}
},
date: {
type: Date, default: Date.now
},
isPublished: Boolean,
price: {
type: Number,
required: true,
min: 10,
max: 1000
}
});

有关更多详细信息:https://mongoosejs.com/docs/validation.html

有时您想模拟异步,例如在这里,创建课程可以在远程服务器上。因此,这里有一个解决方案(从Tags:{validate}中取出SetTimeout,但在单独的函数中调用它

tags: {
type: Array,
validate: {
//isAsync: true,
validator: async function (v) {
await delay(3);
const result = v && v.length > 0;
return result;
},
message: "A Document should have at least one tag!",
},
},

则延迟函数为:

const delay = (n) => {
return new Promise(function (resolve) {
setTimeout(resolve, n * 1000);
});
};

最新更新