Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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

{
    "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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"
        }
      }
    }
  ]
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!