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)
 });
asked Feb 12, 2021 at 12:58
4
  • 1
    if you want to increment number in all object's linkview then try { "affiliatelink.$[].linkview": 1 } Commented Feb 12, 2021 at 13:01
  • As said @turivishal , using the all positional operator $[] should works. Check the documentation and also an example here Commented Feb 12, 2021 at 13:06
  • make sure you have converted adminId to object id if you are using mongoose try mongoose.Types.ObjectId(adminId) Commented Feb 12, 2021 at 13:14
  • thanks a lot @turivishal. Its working now :) Commented Feb 12, 2021 at 13:19

1 Answer 1

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)
});
answered Feb 12, 2021 at 13:14
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.