skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    @Prop(raw({ age: Number, salary: Number, name: String }))
    employees: { age: number; salary: number; name: string}[]
    

    Instead of this:

    @Prop(raw([{ age: Number, salary: Number, name: String }]))
    employees: { age: number; salary: number; name: string}[]
    

  2. I’ve added a arrayFilter in findOneAndUpdate. Try with this one, I hope, it works.

    await this.somethingModel.findOneAndUpdate(
      {
        _id: id,
      },
      {
        $set: {
          "employees.$[elem].salary": 600,
          "employees.$[elem].name": "name4"
        }
      },
      {
        $arrayFilters: [
          {
            "elem.age": 25,
          },
        ],
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search