'Node.js express How update arrays object using PATCH

I have model

  username: {
    type: String,
    required: true,
  },
  firstname: {
    type: String,
  },
  lastname: {
    type: String,   
  },
  email: {
    type: String,
    required: true,
  },
  comments: [
    {
      name: {
        type: String,
      },
      text: {
        type: String,
      },
    },
  ],

And I want update userModel using Controllers this.router.patch(${this.path}/:id, this.editProfile);

  const user = await userModel.findByIdAndUpdate(
    req.params.id,
    {
      ...req.body,
    },
    { new: true, runValidators: true },
  );
  return res
    .status(StatusCodes.OK).send(user)

Everything works but the problem is when I update comments: When I sent req "comments": [ { "name": "coment", "text":"text" } ] It's okay, but when I update without name

        {
        "text":"text2"
        }

the name disappears, but I want that text2 was updated, and the name still exists. What I should use?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source