Mike
Mike

Reputation: 261

Mongodb POST response returns 0?

I got it to work on accident with out adding a res.json(doc) but I found that when I make a POST request I need to send a response and ever since I added that response I get 0 or null?

add: function(req, res) {
    //var newPlayer = new models.Team({ _id: req.params.tid }, { players: req.body });
    models.Team.update({ _id: req.params.tid }, { $addToSet: { players: req.body} }, function(err, newPlayer){
            if (err) {
                res.json({error: 'Error.'});
            } else {
                res.json(newPlayer);
            }
    });
},

Also tried with findOneAndUpdate but my POST request is showing 0 or null for the response.

I am updating an array of objects inside a collection, it's nested. Here is the SCHEMA just to be clear.

var Team = new Schema({
    team_name:   { type: String },
    players: [
        {
            player_name:  { type: String },
            points:       { type: Number },
            made_one:     { type: Number },
            made_two:     { type: Number },
            made_three:   { type: Number },
            missed_one:   { type: Number },
            missed_two:   { type: Number },
            missed_three: { type: Number },
            percentage:   { type: Number },
            assists:      { type: Number },
            rebounds:     { type: Number },
            steals:       { type: Number },
            blocks:       { type: Number },
            fouls:        { type: Number },  
            feed:         { type: String },
            facebook_id:  { type: Number }
        }
    ]
});

So my question is does anyone have any idea why I am getting that response 0?

Upvotes: 0

Views: 98

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

The update method does not return the document in the response. The callback arguments are (err, numAffected) where numAffected is the number of documents touched by the "update" statement, which can possibly do "bulk" ( or multi ) processing.

What you want is findByIdAndUpdate() or findOneAndUpdate(). These methods return the either the original document or the modified document, according to the arguments you give.

add: function(req, res) {
    models.Team.findByIdAndUpdate(
        req.params.tid,
        { $addToSet: { players: req.body } },
        function(err, newPlayer){
            if (err) {
                res.json({error: 'Error.'});
            } else {
                res.json(newPlayer);
            }
        }
    );
},

Upvotes: 1

Related Questions