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

368
Visualizações
Mongoose doesn't auto assign a _id to my array elements when pushing to it, why?

so as the title says, I want mongoose to automatically add an _id field to the objects I push in my array.

Here is my mongoose schema:

var playerModel = new Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Users",
  },
  class: {
    type: String,
    required: true,
  },
  level: {
    type: Number,
    default: 1,
  },
  spells: {
    type: [String],
    default: ["", "", "", "", ""],
  },  
  inventory: [],
  toolbelt: {
    axe: [{}],
    pickaxe: [{}],
    fishingrod: [{}],
    hammer: [{}],
    saw: [{}],
    sewingkit: [{}],
    knife: [{}],
    gemkit: [{}],
    food: [{}],
    potion: [{}],
  },
  gear: {
    weapon: [{}],
    head: [{}],
    chest: [{}],
    gloves: [{}],
    legs: [{}],
    shoes: [{}],
    earrings: [{}],
    ring: [{}],
    necklace: [{}],
  },
  gold: {
    type: Number,
    default: 0,
  },
  bagSize: {
    type: Number,
    default: 20,
  },
  skills: {
    type: [userSkills],
    default: defaultSkills,
  },
});

So ultimately, when I push a new item to my player.inventory, I want mongoose to auto add the _id, but it doesn't. Also in my schema, I define inventory to be just an Array so that I can push different objects that don't have the same structure into it.

So whenever I do this

player.inventory.push(player.toolbelt.pickaxe[0]);

I want my item to have all it's properties from what I inserted and also an _id property auto generated.

Now it looks like this in my db: Image of my Mongo DB field

Hopefully I was cleared and someone can help me :)

Thank y'all !

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For anybody in the future, I fixed my issue by creating a new schema with the strict option set to false:

var inventoryItem = new Schema({}, { strict: false });

and then say that inventory is:

inventory: [inventorySchema],

For some reason this works, but not this:

inventory: [{}, { strict: false }],

so good to know ! :)

Good day !

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