0

I need to update array field in subdocument and that works

User.findOne({ _id: id }, (err, user) => {
    if (!user) res.json({ error: "Email has not be found" });
    user.set({ "files.0.approved": isApproved });
    user.save((err, updatedUser) => {
      return res.send(updatedUser);
    });
 });

Nevertheless, I wonder how can I make it dynamic ? Since here I'm passing index manually - files.0.approved.

I tried using template strings, but it complains.

I also tried referring here, but could not figure it out.

If we assume that I can get index of array with req.body.index, how to prevent it from being hard-coded ?

2
  • How does it complaint while using template strings? Which error are you getting? Commented Oct 27, 2018 at 14:06
  • syntax error, "" expected instead of `` Commented Oct 27, 2018 at 14:08

1 Answer 1

1

I managed to do it this way.

 User.findOneAndUpdate(
    { _id: id, "files._id": file_id },
    { $set: { "files.$.approved": isApproved } },
    (err, updatedUser) => {
      if (err) res.json({ error: "Something went wrong" });
      res.json({ message: "success" });
    }
  );

Apparently, you initially find the file you need to update and then mongoose has $ operator that points to the index that has been found.

Sign up to request clarification or add additional context in comments.

Comments

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.