Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array entry with ObjectId and Number

I am new to mongodb and am trying to make this type of entry:

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            }
        }
    ]
}

Here is my schema code:

const schema = new Schema({
  resources: [
    {
      amount: {
        type: Number,
        required: true,
      },
      resource: {
        _id: {
          type: Schema.Types.ObjectId,
          ref: "Resource"
        }
      }
    }
  ]
});

here is the json code i send

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            }
        }
    ]
}

After processing the request, the following entry is created

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            },
            "_id": "61ebf5d2e47442bd566fe157"
        }
    ],
    "_id": "61ebf5d2e47442bd566fe156",
    "__v": 0
}

Id for the resource was created correctly, but I can’t figure out where the resources._id key came from? Where did I make a mistake?

>Solution :

You have to off _id from schema declaration in the array, after updating schema try inserting new document,

const schema = new Schema({
  resources: [
    {
      _id: false, 
      amount: {
        type: Number,
        required: true,
      },
      resource: {
        _id: {
          type: Schema.Types.ObjectId,
          ref: "Resource"
        }
      }
    }
  ]
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading