13

I have this schema

var StuffSchema = new mongoose.Schema({
    _id: { type: String, required: true, unique: true },
    name: { type: String, required: true }
});

mongoose.model('Stuff', StuffSchema);

Works fine.

Now I need to add another schema "Cargo" containing this

mystuff: { type:[String], ref: 'Stuff', required:true},

that is, I want mystuff to contain array of ids of Stuff, but this fails with validation error when running this code

mongoose.model('Cargo').create( some data...)

if I use an empty array for the mystuff field. It seems to work if I change the Cargo schema to

mystuff: { type:[String], ref: 'Stuff'},

but I want the mystuff field to be required and allow empty arrays

What can I do to make this happen?

FORTRAN
  • 567
  • 1
  • 6
  • 13

1 Answers1

15

Empty arrays are created by default (see also this). The attribute required: true requires the array to have at least one element in it (source code). You can remove that attribute to get your desired behavior.

(Aside, mongoose assigns a default _id field with the type ObjectId to all schemas. Declaring it is unnecessary, and using a string is not typical, although certainly allowed.)

Edit Nov 2017: This is a candidate change in Mongoose 5. See https://github.com/Automattic/mongoose/issues/5139.

ZachB
  • 13,051
  • 4
  • 61
  • 89
  • I don't think the schema type *has* to be ObjectId, it needs to be whatever the type of the identifier property of the referenced schema. See the example in the docs http://mongoosejs.com/docs/populate.html – dafyddPrys Dec 12 '16 at 14:16
  • 5
    As you suggested, the default behaviour has changed since version 5 of Mongoose. Quoting https://mongoosejs.com/docs/migrating_to_5.html#array-required : > 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. – Eric Redon Oct 15 '19 at 11:42