• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

327
Views
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 3 years ago · Santiago Trujillo
1 answers
Answer question

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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error