Elias Garcia
Elias Garcia

Reputation: 7282

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.

Upvotes: 12

Views: 5568

Answers (4)

Deeksha Sharma
Deeksha Sharma

Reputation: 3359

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.

Upvotes: 0

Ciprian B
Ciprian B

Reputation: 550

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) {

})

Upvotes: 3

Pankaj Jatav
Pankaj Jatav

Reputation: 2184

You can use the nested schema in mongoose.

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

Upvotes: 1

Dan Green-Leipciger
Dan Green-Leipciger

Reputation: 3932

Yes, your schema is correct.

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

Upvotes: 8

Related Questions