kevin
kevin

Reputation: 628

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.

Upvotes: 5

Views: 5442

Answers (3)

adel parsa
adel parsa

Reputation: 446

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'}]}

Upvotes: 0

kevin
kevin

Reputation: 628

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: []
    }
}

Upvotes: 5

Asif Saeed
Asif Saeed

Reputation: 2045

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

Upvotes: 0

Related Questions