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 !
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 !