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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.