Darryl Javier
Darryl Javier

Reputation: 170

Update all objects in a MongoDB document array field

What I'm trying to do

I am trying to update all objects inside a field array in a MongoDB document using mongoose.

What I have

User document

{
 id: <ObjectId>,
 ...
 notifications: [
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
  },
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
  },
 ]
}

What I want to have

{
 id: <ObjectId>,
 ...
 notifications: [
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
   read: true // Add read field with a value of true
  },
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
   read: true // Add read field with a value of true
  },
 ]
}

I am working with mongoose which right now I am using the findByIdandUpdate method. I tried using a method to do this but it just failed.

await User.findByIdAndUpdate(
        args.userId,
        {
          notifRead: true,
          $set: {
            "notifications.$.read": true, // FAIL "The positional operator did not find the match needed 
                                          // from the query."
          },
        },
        {
          new: true,
          runValidators: true,
        }
      );

Is there a way to do this simply?

Upvotes: 0

Views: 881

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

It can be possible using all positional operator $[], you can do this:

await User.update(
        args.userId,
        {
          $set: {
            "notifications.$[].read": true,                             
          },
        },
        {
          muti: true
        }
      );

For more details, you can check here.

Upvotes: 1

Related Questions