Daniel Lopes Ferreira
Daniel Lopes Ferreira

Reputation: 33

Mongoose - required validator not running by function

I'm passing a function to required validator in mongoose schema, but it's not firing if i don't pass any value to the field.

In documentation says the following:

Validators are not run on undefined values. The only exception is the required validator.

Reference: https://mongoosejs.com/docs/validation.html

If I pass a function is it not applied?

EDIT - Sharing the code:

My field definition:

field: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Model',
      required: !isBlock,
      autopopulate: true
    }

The function that isn't firing:

function isBlock() {
  return this.type === 'block'
}

Upvotes: 0

Views: 1024

Answers (2)

Daniel Lopes Ferreira
Daniel Lopes Ferreira

Reputation: 33

Debugging I saw that the problem was with the '!' operator in the function call, changing the code to the under I solved my problem.

required: function () { return !isBlock(this.type) }

Upvotes: 2

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5610

I am posting a reference code match with this otherwise Show your code.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const cryptoRandomString = require('crypto-random-string');

const userSchema = new Schema({
    firstName: {
        trim: true,
        type: String,
        required: [true, "firstName is required!"],
        validate(value) {
            if (value.length < 2) {
                throw new Error("firstName is invalid!");
            }
        }
    },
    lastName: {
        trim: true,
        type: String,
        required: [true, "lastName is required!"],
        validate(value) {
            if (value.length < 2) {
                throw new Error("lastName is invalid!");
            }
        }
    },
    email: {
        unique: [true, "Email already registered"],
        type: String,
        required: [true, "Email is required"]
    },
    mobile: {
        unique: [true, "Mobile Number alraedy available"],
        type: String,
        required: [true, "Mobile Number is required"],
        validate(value) {
            if (value.length !== 10) {
                throw new Error("Mobile Number is invalid!");
            }
        }
    },
    password: {
        type: String,
        required: [true, "Password is required"],
        validate(value) {
            if (value.length < 6) {
                throw new Error("Password must be atleast 6 characters!");
            }
        }
    }
});

Upvotes: 1

Related Questions