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.
In Mongoose, subdocuments are documents that are nested in other documents. You can spot a subdocument when a schema is nested in another schema. Note: MongoDB calls subdocuments embedded documents.
It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.
Schemas can be nested to represent relationships between objects (e.g. foreign key relationships). For example, a Blog may have an author represented by a User object. Use a Nested field to represent the relationship, passing in a nested schema.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
Yes, your schema is correct.
The docs for mongoose nested schema (SubDocuments) can be found here
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) {
})
You can use the nested schema in mongoose.
It will also give you he Object Id on each sub schema values as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With