'Can a subdocument be required in mongoose?

Is it possible to have nested schemas in mongoose and have a required validator on the children? Something like this:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

const eventSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  host: {
    type: userSchema,
    required: true
  }
});

I can't find anything in the documentation. Thanks.



Solution 1:[1]

Yes, your schema is correct.

The docs for mongoose nested schema (SubDocuments) can be found here

Solution 2:[2]

i suppose you'll update eventSchema with subdocuments of type user model. you can use { runValidators: true} for update.

eventModel.update({ name: 'YOUR NAME' }, { $push: { host: user } }, { runValidators: true}, function(err) {

})

Solution 3:[3]

You can use the nested schema in mongoose.

It will also give you he Object Id on each sub schema values as well.

Solution 4:[4]

required is a validator added to a schema or subschema in Mongoose (from docs) so yes, you can set the required field to true ( it is false by default) for your subschema or subdocument in Mongoose. The example schema you have created is correct.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Green-Leipciger
Solution 2 Ciprian B
Solution 3 Pankaj Jatav
Solution 4 Deeksha Sharma