Home > Software design >  How to add an object to an array of objects in Nodejs?
How to add an object to an array of objects in Nodejs?

Time:01-05

I'm creating a backend for my React web application and I'm trying to subscribe a user to a match, this match is an object that have an array called "players" and when I click on the join button the username and profilePicture of the user are being dispatched to my backend. The first user info is sent perfectly but when a second user is subscribed the info of the first one is replaced for the second one.

This is my function that push the data:

const playerJoined = async (req, res) => {
  const torneoId = req.params.id;
  const uid = req.uid;
  const profilePicture = req.profilePicture;
  const username = req.username;

  console.log(req.params);

  try {
    const torneo = await Torneo.findById(torneoId);

    if (!torneo) {
      return res.status(404).json({
        ok: false,
        msg: "Torneo no existe por ese ID",
      });
    }

    const newPlayer = {
      profilePicture: profilePicture,
      username: username,
    };

    const nuevoTorneo = {
      ...req.body,
      players: newPlayer,
    };

    const torneoActualizado = await Torneo.findByIdAndUpdate(
      torneoId,
      nuevoTorneo,
      {
        new: true,
      }
    );

    res.json({
      ok: true,
      torneo: torneoActualizado,
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({
      ok: false,
      msg: "Hable con el administrador",
    });
  }
};

My frontend is working well because when I added more users the array of objects shows all the players like this:

players: (2) [{…}, {…}]

But on my mongo DB shows only the last user info added like I mentioned before.

I really appreciate any help.

CodePudding user response:

You seem to be replacing the players property instead of pushing into it.

const nuevoTorneo = {
  ...req.body,
  players: newPlayer,
};

When you grab the torneo by id, you should have access to that players property already, so spread that array into your nuevoTorneo as well:

const nuevoTorneo = {
  ...req.body,
  players: [...torneo.players, newPlayer],
};

CodePudding user response:

It is because you always put your newPlayer into the "player" field of your nuevoTorneo and updated the same document. I assume you are using mongoose, You probably should just modify the "torneo" after your query and do something like this:

const torneo = await Torneo.findById(torneoId);
const newPlayer = {
  profilePicture: profilePicture,
  username: username,
};
torneo.nuevoTorneo.players.push(newPlayer);
await torneo.save();

Or to simply modify your code as:

const nuevoTorneo = {
  ...req.body,
  players: [...torneo.nuevoTorneo.players,newPlayer],
};

I recommend the first method, let me know if you have any questions.

  •  Tags:  
  • Related