Search code examples
node.jsmongodbmongoosemongoose-schema

How to add new property to object that I findByID in Mongoose?


I have an object in mongodb that i want to add new player its property called players. enter image description here

I have have created a router with findByIdAndUpdate but couldn't success to add new player to my players property.This is how I created it. It is not adding new one, but it updates the old property. I looked on mongoose document and looked at StackOverflow, I can't find how to do it.

router.post("/addPlayer/:id", (req, res) => {
  const id = req.params.id;
  Item.findByIdAndUpdate(
    id,
    { players: { name: "mehmet", age: 25 } },
    function (err, docs) {
      if (err) {
        console.log(err);
      } else {
        console.log("Updated User : ", docs);
      }
    }
  );
});

Here I want to add new player to for example,

 {player:'ali',age:22}

Solution

  • Players is an array if you want to append new players to it you can use $push like this:

    router.post("/addPlayer/:id", (req, res) => {
      const id = req.params.id;
      Item.findByIdAndUpdate(
        id,
        { $push: { players: { name: "mehmet", age: 25 } }},
        function (err, docs) {
          if (err) {
            console.log(err);
          } else {
            console.log("Updated User : ", docs);
          }
        }
      );
    });
    

    If you want to update the first index you can check here for reference.