benjiman
benjiman

Reputation: 4048

Mongoose make Array required

I've got a mongoose model that looks something like this:

var ProjectSchema = new Schema({
    name: { type: String, required: true },
    tags: [{ type: String, required: true }]
});

I want it to be required for a project to have at least one tag. However when I save a new project without a tags array, mongoose does not throw an error:

var project = new Project({'name': 'Some name'});
project.save(function(err, result) {
    // No error here...
});

What am I missing here? How can I specify an array to be required?

Upvotes: 32

Views: 21656

Answers (3)

Yu-An Chen
Yu-An Chen

Reputation: 604

Mongoose 5.x

https://mongoosejs.com/docs/migrating_to_5.html#array-required

tags: {
    type: [String],
    validate: v => Array.isArray(v) && v.length > 0,
}

Mongoose 4.x

One-liner would be:

tags: {type: [String], required: true}

SchemaTypes

Upvotes: 58

Abdelrhmanshokr
Abdelrhmanshokr

Reputation: 7

OK I tried a new method and it seems to work just fine for mongoose ^5.11.15 I'm not really sure if it's a proper answer in terms of clean code but as far as the functionality which is to make an array of Numbers/Strings required (meaning it won't accept an empty array) it works OK so it's as follows

size: [{
        type: Number,
        required: true
}],

instead of

size: {
        type: [Number],
        required: true
},

Instead of defining the type as an array of numbers/strings, I defined the size to be an array of numbers and then the required attribute works as it should it doesn't accept an empty array and raises an error to illustrate that. again I'm not really sure if this is the best way to define a required array but as far as the functionality it works just fine

Upvotes: 1

robertklep
robertklep

Reputation: 203319

AFAIK, you need to set the type to Array and add a custom validator to make sure that each entry is a String:

tags : {
  type     : Array,
  required : true,
  validate : {
    validator : function(array) {
      return array.every((v) => typeof v === 'string');
    }
  }
}

Upvotes: 11

Related Questions