Search code examples
mongodbmongoosemongoose-schema

How to define mongoose schema for nested documents


I need to define the mongoose schema for for nested documents which is given below.

Documents:

"Options":[{"Value":["28","30","32","34","36","38","40","42","44","46"],"_id":{"$oid":"5de8427af55716115dd43c8f"},"Name":"Size"},{"Value":["White"],"_id":{"$oid":"5de8427af55716115dd43c8e"},"Name":"Colour"}]

I was declaring like below but its not working.

const Product = new Schema(
  {
    Options: [{ value: { _id: ObjectId, Name: String } }]
  },
  {
    timestamps: {
      createdAt: "createdAt",
      updatedAt: "updatedAt"
    },
    collection: "products"
  }
);

Here I need the schema where if i will directly add/update the same document then it will be added.


Solution

  • You need to modify your schema like this :

    {
        Options: [ new Schema ({ value: [...], _id: Schema.Types.ObjectId, Name: String })]
    }
    

    This is the way to create an array of subdocuments with Mongoose. If you don't use the "new Schema" key words, you are actually creating a field with type "Mixed", which needs a different way to handle updates.

    You can also omit the _id, it should be added automatically.

    You can find more information on subdocument on this page : https://mongoosejs.com/docs/subdocs.html

    ...and on mixed type fields : https://mongoosejs.com/docs/schematypes.html#mixed

    ...which will explain shortly the problem.