Zak
Zak

Reputation: 940

How can I update a document's nested array of object item by 1?

I'm trying to update a mongoose document with the help of findOneAndUpdate but I'm unable to do so. The document looks like this in the database:

{
    'docId': 1001,
    'totalViews': 3,
    'docInfo': [
         {
             id: 1,
             views: 2  
         },
         {
             id: 2,
             views: 1  
         }
    ]
}

I'm trying to update totalViews by 1 which will make the total count to be 4. And I also need to update the second object's views property by 1 in imageInfo array. Which will have a views count of 2.

I tried doing this by first fetching the whole document with the help of:

const doc = await Doc.find({ docId: 1001 });

Then found the index of the docInfo array item which needs to be updated. Which is the object with id 2.

const docIndex = doc[0].docInfo.findIndex( item => {
      return item.id === 2;
});

Then used findOneAndUpdate to update the items:

await Doc.findOneAndUpdate(
      { docId: 1001, "docInfo.id": 2 },
      {
            $set: {
                  [ `docInfo.${2}.views` ]: 1++,
                  'totalViews': 1++ 
            }
      }, { new: true }
);

With this I'm getting this error:

SyntaxError: Invalid left-hand side expression in postfix operation

What am I doing wrong here?

Upvotes: 1

Views: 83

Answers (1)

turivishal
turivishal

Reputation: 36154

What you are doing is invalid, you can use $inc operator to increment a number, and don't need to find a query as well,

await Doc.findOneAndUpdate(
  { docId: 1001, "docInfo.id": 2 },
  {
    $inc: {
      'docInfo.$.views': 1,
      'totalViews': 1
    }
  }, 
  { new: true }
);

Playground

Upvotes: 1

Related Questions