简体   繁体   中英

Mongoose saves without a required field

I am trying to test Mongoose schemas by inserting an object which is not included with some required field.

This is the case:

let schema = {
    _supplier: {
      type: Schema.Types.ObjectId,
      required: true
    },
    permissions: {
      type: [
        {
          level: {
            type: Number,
            min: 1,
            max: 9,
            required: true
          },
          title: {
            type: String,
            minlength: 0,
            maxlength: 16
          },
          modules: [String]
        }
      ],
      validate: [permissionsLimit, '${PATH} exceeds the limit of 9'],
      required: true
    }
  };

  function permissionsLimit(v) {
    return v.length<=9;
  }

  let permissionsTestSchema = new Schema(schema);

  let PermissionsTest = mongoose.model("permissionsTestSchema", permissionsTestSchema);

  let permissionTest = new PermissionsTest({
    _supplier: mongoose.Types.ObjectId()
  });

  permissionTest.save(err => {
    if (err) return cast.error(err);
    return cast.ok();
  });

As you can see, I make an instance which only contains the _supplier key - I don't add the permissions array - Which is required .

Instead of receiving an error, the Mongoose applies the action and inserts a blank array of permissions to the collection in MongoDB.

This is not the behaviour I need in here. I don't wand a document in the collection which has missing details.

If user do not provide with permissions array to his value, I do not accept the query at all.

Why Mongoose ignores the required field in the schema?

Arrays in mongoose have one special feature:

Arrays are special because they implicitly have a default value of [] (empty array).

To overwrite this default, you need to set the default value to undefined

So you can change your schema to:

let schema = {
    _supplier: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
    },
    permissions: {
        type: [
            {
                level: {
                    type: Number,
                    min: 1,
                    max: 9,
                    required: true
                },
                title: {
                    type: String,
                    minlength: 0,
                    maxlength: 16
                },
                modules: [String]
            }   
        ],
    validate: [permissionsLimit, '${PATH} exceeds the limit of 9'],
    required: true,
    default: undefined
    }
};

and then your code will throw an exception with following message:

UnhandledPromiseRejectionWarning: ValidationError: permissionsTestSchema validation failed: permissions: Path permissions is required.

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