0

I can't handle updating array of objects in my database, tried many options but nothing worked. Im pretty sure that the answer is obvious, but I couldn't manage it since wednesday. Here is my kitSchema:

const kitSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  kit: {
    type: Array,
    required: true,
  },
  profiles: {
    type: Array,
    required: true,
  },
});

module.exports = mongoose.model("Kit", kitSchema);

All users have their own document, and there are also profiles in it. I want to update single profile by passing the id of user and id of profile. Example of data:

_id: 1,
email: "abc@mail",
password: "abc",
profiles: [
           {
            id: 1,
            name: John
           },
          ]

And here's my latest solution which doesn't work:

router.put("/profile/:id", async (req, res) => {
  let kit = await Kit.findById(req.params.id, (error, data) => {
    if (error) {
      console.log(error);
    } else {
      console.log(data);
    }
  });
  try {
    await kit.profiles.findOneAndUpdate(
      { id: req.body.id },
      { name: req.body.name },
      { new: true },
      (error, data) => {
        if (error) {
          console.log(error);
        } else {
          console.log(data);
        }
      }
    );
    try {
      res.status(202).json({ message: "Changed" });
    } catch (err) {
      res.status(400).json({ message: err });
    }
  } catch (err) {
    res.status(400).json({ message: err });
  }
});

Could you give me a hand with this?

1 Answer 1

1

As always, after days of trying I've got answer 10 minutes after asking question. Here's what I came up with:

router.put("/profile/:id", async (req, res) => {
  await Kit.findOneAndUpdate(
    { _id: req.params.id, profiles: { $elemMatch: { id: req.body.id } } },
    {
      $set: {
        "profiles.$.name": req.body.name,
        "profiles.$.profilePicture": req.body.profilePicture,
      },
    },
    { new: true, safe: true, upsert: true },
    (error, data) => {
      if (error) {
        console.log(error);
      } else {
        console.log(data);
      }
    }
  );
  try {
    res.status(202).json({ message: "Changed" });
  } catch (err) {
    res.status(400).json({ message: err });
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.