Search code examples
javascriptnode.jsmongodbrelationshipnon-relational-database

Sending relational data updates from front-end to back-end


I have a table which holds different persons. Now the user can select a set of persons (say Tom Dick & Harry) and group them into a new "team". In the backend i would need to update Tom, Dick & Harry and add a team-id to their team_field.

e.g.:

{
name: "Tom",
age: 12,
team_id: id_for_team_1
}

But since team_1 did not exist before the user selected Tom,Dick & Harry and created the team, I do not yet have an id for team1.

I need this first it seems:

{
_id: id_for_team_1
team_name: "Team Cool"
team_color: "blue"
}

How would I solve this in the front-end?

My idea: Make a request to the backend to create the team on the server, get the team_id back from the backend, and then add the id to to Tom, Dick & Harry and then send their updates profiles to the backend?

But: is this the simplest approach I could take, or are there better ways to solve this? It seems complicated. Ideally, I would like to just update everything in the front-end, that is, create a team object + update profiles, and then send it all to the server in one go. But I don't know how I could do this, since I seem to be dependent on mongodbs ids and cannot just make up my own in the frontend.


Solution

  • In case you just want to update the teams they belong you can just in one call sending a list of userIds, and the backend can then create a new team and also update the team_id. Pseudocode:

    1) POST /api/team
    2) let userIds = req.body.userIds
    3) newTeamId = Create a new team in Mongo and get its id
    4) for(uid in userIds){ 
        user = Mongo.find(id : uid);
        user.teamId = newTeamId 
        Mongo.update(user)
     }
    

    If you also want to be able to update users information, I would create 2 API methods, one for updating the user profile and another to manage the teams.