user3488537 user3488537 - 6 months ago 23
Node.js Question

mongoose update a value in a document using model.update

What am i doing wrong here, I want to update the score?

the problem is it executes the code without errors but doesn't update the score.

Team.findOne({name: req.body.team}, function(err, teamData){
if(teamData) {
var a = teamData.score + 1;
Team.update({name: req.body.team},{$set: {score : a}});
}
else {
console.log(err);
}
});

Answer

As Muhammad Ali said, update requires a callback function, that is probably your problem. But there is also an easier way to do this:

Team.findOne({name: req.body.team}, function(err, teamData){            
    if(teamData){
        teamData.score += 1
        teamData.save(function(err) {
            if (err) // do something
        });
    }else{
        console.log(err);
    }
});