'Callback is not function

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
    }
});


Solution 1:[1]

Please dont use setTimeout in validator. As you only want to validate the value immediately and dont use callback. As you only return true or false in validator.

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
}
});

For more details: https://mongoosejs.com/docs/validation.html

Solution 2:[2]

Sometimes you want to simulate an async, for example here, creating the course could be on a remote server. So, here is a solution (taking SetTimeout out of Tags:{ validate} but calling it in a separate function.

  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!",
    },
  },

Then the delay function is:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asad Haroon
Solution 2 Pick Avana