I’m trying to update multiple fields of a object in an array but it doesn’t work.
what am i doing wrong?
Data Sample:
{
_id: 'mongodbid',
name: 'something',
employees: [
{
age: 25,
name: 'name',
salary: 500
},
{
age: 28,
name: 'name2',
salary: 700
}
],
}
Query:
await this.somethingModel
.findOneAndUpdate(
{
_id: id,
'employees.age': 25,
},
{
$set: {
'employees.$.salary': 600,
'employees.$.name': 'name4',
}
},
)
.exec();
2
Answers
Turns out problem wasn't with the query itself, rather the schema. I forgot to add [ ] to the employees field in the schema.
I was using 'raw' from '@nestjs/mongoose' package, I mistakenly wrote this:
Instead of this:
I’ve added a
arrayFilter
infindOneAndUpdate
. Try with this one, I hope, it works.