我正试图在node.js中的异步mongodb模式验证器中保存一个文档。我在mongodb架构中设置了一个自定义验证"标记"命名属性。"tag"中的验证程序是异步的。该程序将文档添加到mongodb中,但在4秒钟后(setTimeout(((,它会给出回调不是函数的错误。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('Connected with MongoDB...'))
.catch(err => console.log("Couldn't connect with MongoDB!!!", err));
const courseSchema = new mongoose.Schema({
name: { type: String, required: true, minlength: 3, maxlength: 55 },
author: String,
edition: Number,
categories: {
type: String,
enum: ['web', 'mobile', 'research', 'networking'],
required: true
},
tags: {
type: Array,
validate: {
isAsync: true,
validator: function (v, callback) {
setTimeout(() => {
const result = v && v.length > 0;
callback(result);
}, 4000);
},
message: 'A course should have at least one tags'
}
},
data: { type: Date, default: Date.now },
isPublished: Boolean,
price: { type: Number, min: 5, max: 50, required: function () { return this.isPublished } }
});
const Course = mongoose.model('Course', courseSchema);
async function createCourse() {
const course = new Course({
name: "Compiler Constructions",
author: "Mudassir",
edition: 2,
categories: 'web',
tags: ['CUI'],
isPublished: false,
price: 8
});
try {
const result = await course.save();
console.log(result);
}
catch (err) {
console.log(err.message);
}
}
createCourse();
基于文档和承诺,试试这个:
tags: {
type: Array,
validate: {
validator: function (v) {
return new Promise((resolve) => {
setTimeout(() => {
const result = v && v.length > 0;
resolve(result);
}, 4000);
});
},
message: 'A course should have at least one tags',
},
},