Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

366
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda