Reputation: 1735
I am trying to update a single element in an array of references using the following syntax:
Company.findOneAndUpdate({
_id: mongoose.Types.ObjectId("5ec424a1ed1af85a50855964"),
departments: {
"$elemMatch": {
"id": mongoose.Types.ObjectId("5ec424a1ed1af85a508558495")
}
}
}, {
$set: {
"departments.$.active": true
}
});
Here is the schema definition:
const companySchema = new Schema({
departments: [{
id: {type: Schema.Types.ObjectId, ref: "Department"},
active: {type: Schema.Types.Boolean},
}]
});
When I run this code it does not update the database as it still reflects the original value. I am not understanding why this is not working. From the resources I reviewed online, this seems to be the approach. What am I doing wrong?
Upvotes: 1
Views: 215
Reputation: 521
You can try this one, It might help you
Company.findOneAndUpdate(
{
_id: mongoose.Types.ObjectId("5ec424a1ed1af85a50855964"),
},
{
$set:{
"departments.$[el].active": true
}
},
{
arrayFilters:[{
"el.id":mongoose.Types.ObjectId("5ec424a1ed1af85a508558495")
}]
}
)
Upvotes: 1