When I update a document and push an object to an array (here below I push a new object containing info and date into the report array), an id is always being added and pushed into it. Why is that? Whats wrong in my code?
I create:
report: {
info: 'abc',
date:...,
_id: "'123'
}
but its suppose to be just:
report: {
info: 'abc',
date:...
}
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
hasReport: {
type: Boolean
},
// if there is no reports, it will be an empty array, if there is i just push a new object into the array
report: [{
info: String,
date: Date
}],
}
mongoose.model('Product', productSchema);
updateProduct: async (req, res) => {
const { id, hasReport, report: {info}} = req.body;
const station = await Product.findByIdAndUpdate({_id: id}, {
$push: {
report: {
info: info,
date: new Date()
},
}, $set: {hasReport: true}})
product.save()
}
2
Answers
Try to create report schema as:-
it should work for you.
Object inside array is also considered as doc in MongoDB. So, it will auto create id for each. If you want to disable this behaviour for objects of array then you can do it from your schema file.