I have a simple schema with an array in there. When I create a new item including items in the mapping array, the items in the mapping array are automatically assigned an _id. However, when I try to add items to the mapping array of an existing item, the new mapping is created with an _id of null. How do I get mongoose to generate this _id for me? I can't find it anywhere in the documentation.
My schema is:
{
email: {
type: String,
required: true,
index: true,
},
mapping: [
{
mapToField: {
type: String,
enum: [
"subject",
"location",
"company",
"hours",
"rate",
"startDate",
"endDate",
],
required: true,
},
mapToLabel: {
type: String,
required: true,
},
regex: {
type: String,
required: true,
},
},
],
},
{ timestamps: true }
);
I have tried two ways to add an item to the mapping array but both options result in an item being added without an _id.
Option 1:
let item = await Mappings.findOne({ _id: id });
return await item.mapping.create(mapping);
Option 2:
return await Mappings.update(
{ _id: id },
{ $push: { mapping } },
{ upsert: true }
);
How do I get mongoose to generate an _id for the items in the mapping array?