Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 388
Elias Garcia Avatar asked Apr 25 '17 21:04

Elias Garcia


People also ask

What is a subdocument in Mongoose?

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.

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.

Can you have a schema within a schema?

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.

Does Mongoose auto generate ID?

_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.


3 Answers

Yes, your schema is correct.

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

like image 50
Dan Green-Leipciger Avatar answered Oct 13 '22 17:10

Dan Green-Leipciger


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

})
like image 3
Ciprian B Avatar answered Oct 13 '22 16:10

Ciprian B


You can use the nested schema in mongoose.

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

  • Doc: Here
  • Example: Here
like image 1
Pankaj Jatav Avatar answered Oct 13 '22 18:10

Pankaj Jatav