1

Hi I tried to update the element at a particular index in an array but I'm not able to update it. It is updating the entire array. Not able to figure out how to update any particular index which is being passed by user. Let say user pass index from frontend as 1 then only the element at index 1 in appointment array gets updated not other. Let say I have a schema in which I have Data who's type is array and default value is as shown below or anything in the same format.

Data: {
  type: Array,
  Default: ["0","1","0"]
}

Whenever I'll create a user then Data field will contain these default values, But now I want to update the value at index 1 of Data array of any user created.

I tried findByIdAndUpdate method but I don't know what to pass in set property. If I'm passing this {$set: req.body} and In postman I'm giving any value of Data then obviously it is updating Data array but I want to update value at any index how should I do that. What changes I have to make in {$set : }? Or any other method for that? Thanks in advance.

Waiting for any help or suggestions. Thanks

2
  • first find the user. Then once you find the document you can do something like ` const subDoc =user.keyName.id(passInTheIdOfTheSubdocument then mutate the subDoc however you want then you can save() the document again Commented Jan 31, 2023 at 18:00
  • Hello, Subhanshu You can see your answer to this question at stackoverflow.com/questions/71468041/… Commented Oct 8, 2024 at 11:13

0

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.