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

1.1K
Views
Mongoose how to auto add _id to objects in array within collection item?

i have a mongo collection that looks like this:

{
    name: string
    _id: (auto set)
    items: array[
        name: string
        url: string
        items: array[
            {
                name: string,
                url: string,
                items: []
            }
        ]
    ]
}

I'm using findByIdAndUpdate (with mongoose) to add an item into the items array:

Menu.findByIdAndUpdate(
    req.body.parentid, 
    {
        $push: {
            items: {
                name: req.body.item.name, 
                url: req.body.item.url,
                items: []
            }
        }
    },
    {
        safe: true, 
        upsert: true, 
        new: true
    },
    function(err, model) {
        if (err !== null) {
            console.log(err);
        }
    }
);

This works fine, but it does not add an _id to each object inserted into the items array. And i really need an id for each one.

I'm guessing it comes from the method used, findByIdAndUpdate as it looks more like an update rather than an insert. If my thinking is correct.

Using mongodb 3.2.10 and mongoose 4.7.6.

Any help would be really appreciated. Thanks.

EDIT: the _id: (auto set) is not real, it's being automatically added via mongo. But just at the top level objects.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Found the solution in this thread: mongoDB : Creating An ObjectId For Each New Child Added To The Array Field

basically, added

var ObjectID = require('mongodb').ObjectID;

and then forcing the creation:

$push: {
    items: {
        _id: new ObjectID(),
        name: req.body.item.name, 
        url: req.body.item.url,
        items: []
    }
}
over 4 years ago · Santiago Trujillo Report

0

You dont need to sepcify _id: (auto set) in mongoose schema it will automatically add unique _id with each document.

over 4 years ago · Santiago Trujillo Report

0

if you don't define _id in Schema, mongoose automatically add a _id to array item. for example:

const countrySchema = new Schema({
  name: {
    type: String
  },
  cities: [
    {
      // don't define _id here.
      name: String
    }
  ],
});

now when you insert a row, the result is something like this:

{name : 'Iran', cities : [{_id : 6202902b45f0d858ac141537,name : 'Tabriz'}]}

over 4 years ago · Santiago Trujillo 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!