【问题标题】:TypeError: callback is not a function at Timeout._onTimeoutTypeError:回调不是 Timeout._onTimeout 的函数
【发布时间】:2021-11-29 05:42:19
【问题描述】:

我正在尝试将文档保存在 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();

【问题讨论】:

  • 您在文档中的什么地方看到验证器获取两个这样的参数?也许我错过了它,但我没有看到它。
  • 'validator'中的函数有两个参数。 Mosh Hamedani 的 node.js 课程也是如此。
  • 我仍然没有在文档中看到它,并且错误表明它没有,或者至少它不是一个函数。你打印出来看看你得到了什么?

标签: javascript node.js mongodb validation mongoose


【解决方案1】:

基于docspromise,试试这个:

  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',
    },
  },

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2018-01-22
    • 2018-06-05
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2018-09-16
    相关资源
    最近更新 更多