0

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?

Darryl Javier
  • 150
  • 1
  • 3
  • 8

1 Answers1

1

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.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35