Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda