1

I can't get my req.body inserted into my mongodb collection.

I have this route that triggers the add method and inside I am trying to figure out a query to save the req.body into a nested collection array

router.post('/api/teams/:tid/players', player.add);

add: function(req, res) {
    var newPlayer = new models.Team({ _id: req.params.tid }, req.body);
    newPlayer.save(function(err, player) {
        if (err) {
            res.json({error: 'Error adding player.'});
        } else {
            console.log(req.body)
            res.json(req.body);
        }
    });
}

Here is an example document

[
   {
      "team_name":"Bulls",
      "_id":"5367bf0135635eb82d4ccf49",
      "__v":0,
      "players":[
         {
            "player_name":"Taj Gibson",
            "_id":"5367bf0135635eb82d4ccf4b"
         },
         {
            "player_name":"Kirk Hinrich",
            "_id":"5367bf0135635eb82d4ccf4a"
         }
      ]
   }
]

I can't figure out how to insert/save the POST req.body which is something like

{
    "player_name":"Derrick"
}

So that that the new req.body is now added into the players object array.

My question is how do I set the mongodb/mongoose query to handle this?

P.S I am obviously getting the error message because I don't think the query is valid, but it's just kind of an idea what I am trying to do.

Something like this is more suitable, still doesn't work but its a better example I guess

var newPlayer = new models.Team({ _id: req.params.tid }, { players: req.body });

1 Answer 1

1

If you created a Team model in Mongoose then you could call the in-built method findOneAndUpdate:

Team.findOneAndUpdate({ _id: req.params.tid }, 
                      { $addToSet: { players: req.body} }, 
                        function(err, doc){
                              console.log(doc);
                      });

You could do findOne, update, and then save, but the above is more straightforward. $addToSet will only add if the particular update in question doesn't already exist in the array. You can also use $push.

The above does depend to an extent on how you have configured your model and if indeed you are using Mongoose (but obviously you asked how it could be done in Mongoose so I've provided that as a possible solution).

The document for $addToSet is at http://docs.mongodb.org/manual/reference/operator/update/addToSet/ with the relevant operation as follows:

db.collection.update( <query>, { $addToSet: { <field>: <value> } } );
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks just now saw this, this looks good let me try it out :)
This worked well, it's nice to finally see the data added to my DB , but for some reason the POST request doesn't completely finish it just hangs, but the data does reach the server nicely. Just thought I would mention that, but thanks for the answer it's nice that I can get the data stored, I may just need to tweak a few things to get that POST to work like it should, the problem could be somewhere else. THANKS
Glad to hear the data is now being stored. Certain methods of POST requests would expect a response of some kind res.json(doc:doc)) for example) so maybe that is something to think about.
Yeah I had to open a new question I didnt realize that, I figured it out and learned something along the way. I had an id issue but I worked that out, now I am trying to configure the client side backbone.js to use the correct id in the url path.. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.