I have a node application using MongoDB 7.0.5 Community, Mongoose 7.6.8, MongoDB drivers 6.3.0 and Node version 20.10.0.
I can’t get this code to work:
const updatedDealer = await my_model.updateMany(
{
CustomerId: 123,
'Vehicles.Id': { $in: IdArray }
},
{
$set: { 'Vehicles.$.FieldsToUpdate': true }
},
{
multi: true
}
);
IdArray is literally an array of numbers. My Mongoose model is correct, because if I update a single record using:
const updatedDealer = await my_model.findOneAndUpdate(
{
CustomerId: 123,
'Vehicles.Id': 123456
},
{
$set: { 'Vehicles.$.FieldsToUpdate': true }
},
{
new: true
}
);
It works.
Nether CustomerId or Vehicles.Id are MongoDB _ids.
This is a simplified example of my data:
[{
CustomerId: 123,
CustomerName: 'Some Company',
Vehicles: [
{
Id: 123456,
Make: 'Ford',
Model: 'Focus',
FieldsToUpdate: false
},
{
Id: 543213,
Make: 'Kia',
Model: 'EV9',
FieldsToUpdate: false
}
]
}]
And a simplified example of my model:
const my_model = mongoose.Schema({
CustomerId: {
type: Number
},
CustomerName: {
type: String
},
Vehicles: [
{
Id: {
type: Number
},
Make: {
type: String
},
Model: {
type: String
},
FieldsToUpdate: {
type: Boolean
}
}
]
})
Would appreciate any help with this one. Thanks.
2
Answers
you could use an arrayFilter to update the subdocuments you want.
See on mongoplayground.
Mongoose V7 doesn’t have a
Model.update()
method, it was removed in V7.You can use
Model.updateMany()
as follows: