1

im very new with nodejs. Currently, im doing a increment a value into an array object. I have an error after write this code. I want to increment the value of linkview. i found something similar with my problem Mongoose - Increment a value inside an array of objects but i still cannot solve it. Please help

So this is User schema

{        
  "_id": "67324b2cc6817758118e9557d8",
  "name": "James",
  "__v": 0,
  "affiliatelink": [
    {
      "storeId": 60014d6e7286763490c3543,
      "storeName": white choc,
      "linkview": 1
    }
  ]
}`


and this is my code and the error is MongoError: The positional operator did not find the match needed from the query


Admin.findByIdAndUpdate({ _id: adminId }, {$inc: {"affiliatelink.$.linkview": 1}}, function(err, result) {
        console.log("ni error "+err)
        //if (err) return next(err)
    });
  • 1
    if you want to increment number in all object's `linkview` then try `{ "affiliatelink.$[].linkview": 1 }` – turivishal Feb 12 '21 at 13:01
  • As said @turivishal , using the all positional operator `$[]` should works. Check the [documentation](https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up._S_[]) and also an example [here](https://mongoplayground.net/p/BFP3XrnawGr) – J.F. Feb 12 '21 at 13:06
  • make sure you have converted `adminId` to object id if you are using mongoose try `mongoose.Types.ObjectId(adminId)` – turivishal Feb 12 '21 at 13:14
  • thanks a lot @turivishal. Its working now :) – husna yaman Feb 12 '21 at 13:19

1 Answers1

0

You need to specify which object to update in the array of objects affiliateLink

You can use the below query and give it a try:

Admin.findOneAndUpdate(
   {
     _id: adminId, 
     "affiliateLink.storeId": "60014d6e7286763490c3543"
   },
   {
     $inc: {
          "affiliateLink.$.linkView": 1
     }
   }, 
   function(err, result) {
        console.log("ni error "+err)
        //if (err) return next(err)
});

Roshan Raj
  • 173
  • 2
  • 10