简体   繁体   中英

Required property doesn't work for array of ObjectId type in mongoose

I have the following schema and model for mongoose:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    first_name: String,
    second_name: String,
    roles: { type: [{ type: Schema.Types.ObjectId, ref: 'Role' }], required: true }
});

userSchema.virtual('fullName').get(function() {
    return `${this.first_name} ${this.second_name}`;
});

module.exports = mongoose.model('User', userSchema);

I can't get required to work for arrays of ObjectId , when I create an object without the roles field and save it mongoose doesn't throw and error. What am I doing wrong here?

In mongoose V4 the required on the array worked as you wanted.

But in V5 this behavior has been changed .

In mongoose 5 the required validator only verifies if the value is an array. That is, it will not fail for empty arrays as it would in mongoose 4.

But you can use the validate function to make it work. Returning false or throwing an error means validation failed.

So if you want to validation to fail when the array is null or empty, you can use the following validate function.

validate: v !== null && v.length > 0

Test:

const validate = (v) => {
  return v !== null && v.length > 0;
};

const res1 = validate(null);
console.log(res1); // FALSE  => Validation fails

const res2 = validate([]);
console.log(res2); //FALSE  => Validation fails

const res3 = validate([1, 2]);
console.log(res3); //TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM