0

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}
Apoorva Chikara
  • 1
  • 3
  • 18
  • 29
sayinmehmet47
  • 347
  • 2
  • 10

2 Answers2

0

Since its an array, you can just simply do a push and save.

Sammy
  • 66
  • 2
0

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.

Apoorva Chikara
  • 1
  • 3
  • 18
  • 29