1

I am trying to push to a document then set isDefault to false for all except for the one I want to set. I am having issues setting it as I am getting MongoError: Updating the path 'cards' would create a conflict at 'cards'

this is my query

    const update = { 
                
                $push: { cards: card },
                $set : { 'cards.$[].isDefault': false },
            };

const query = { id: customer.id }

this.model.findOneAndUpdate(
                query,
                update,
                { new: true },
                (err, result) => {
                    if (err) {
                        return reject(err);
                    }

                    if (!result) {
                        return reject(
                            new ModelNotFoundError(
                                `${this.name} not found update with operators`
                            )
                        );
                    }

                    resolve(result);
                }
            );

This is what my data structure looks like

[
  {
    id: 1,
    cards: [
      {
        name: "Shipit",
        fee: 4,
        isDefault: false
      },
      {
        name: "Shipit",
        fee: 3,
        isDefault: true
      }
    ],
    
  },
  {
    id: 2,
    cards: [
      {
        name: "Shipit",
        fee: 3,
        isDefault: true
      }
    ],
    
  }
]
prasad_
  • 12,755
  • 2
  • 24
  • 36
King
  • 1,885
  • 3
  • 27
  • 84

1 Answers1

0

You can try this for the update (works without any errors and the result is as expected), using the Updates With Aggregation Pipeline feature (requires MongoDB v4.2+).

update = [
  { $set: { 
    cards: { 
      $map: { 
        input: "$cards", 
        in: { $mergeObjects: [ "$$this", { isDefault: false } ] }
      }
    }
  } },
  { $set: { 
    cards: { 
      $concatArrays: [ "$cards", [ card ] ] 
    }
  } }
]

The error you are getting is due to performing two update operations ($set and $push) on an array field.

prasad_
  • 12,755
  • 2
  • 24
  • 36