Search code examples
node.jsarraysmongodbmongooseupdates

Update element of any particular index in an array in MongoDb using Mongoose in Node.js


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. Also tried {$set:{"Data.1:req.body}}. this is updating at 1st index but I don't want to hardcode the index value. It should take from frontend. 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 any index (coming from frontend) 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 which I'm passing from frontend, let say the index I'm passing is 2 then it should update the value of array at index 2, similarly I can pass any index from frontend how should I do that.
What changes do I have to make in {$set : }?


Solution

  • It appears that you can solve this in backend logic if you are passing the index from the frontend.

    You can dynamically specify the index, based on the input from the frontend, before you send a query.

    const updateUserData = async (req, res) => {
      const { index, user_id, new_value } = req.body;
    
      try {
        const update = {};
        update[`Data.${index}`] = new_value;
    
        const data = await Users.updateOne(
          { _id: user_id  },
          { $set: update }
        );
    
        return res.status(200).json({ success: true  });
      } catch (error) {
        return res.status(500).json({ success: false });
      }
    };