I'm using Sails.js, and trying to increment an attribute in my model by one when a function is called. It works and increments and return JSON with the value as 1, but never saves to the database, so when I make a get request later, the value is still 0.
Function:
addVote: function (req, res, next) {
Nomination.findOne(req.param('id'), function foundNomination(err, nom) {
if(err) return next(err);
if(!nom) return next();
Nomination.update(req.param('id'), {
votes: nom.votes++
})
return res.json({
votes : nom.votes
});
});
},
EDIT:
Now this is weird. Must be some scoping issue. When I change the code to this, the console outputs 0 then 1. If I take out the second console.log, it outputs 1...
addVote: function (req, res, next) {
var newVotes = 0;
Nomination.findOne(req.param('id'), function foundNomination(err, nom) {
if(err) return next(err);
if(!nom) return next();
nom.votes++;
newVotes = nom.votes;
console.log(newVotes);
});
console.log(newVotes);
Nomination.update(req.param('id'), {
votes: newVotes
}, function(err) {
if(err) return res.negotiate(err);
return res.json({
votes : newVotes
});
});
},
AHHA! It's calling the Update function before findOne. But why, and how do I stop it?
I think you have to do this :
nom.votes++; //or nom.votes = nom.votes+1;
Nomination.update(req.param('id'),
{
votes: nom.votes
}).exec(function(err, itemUpdated)
{
if(err)//error
{
//manage error
}
else
{
res.json({
votes : itemUpdated.votes
});
}
});
All database access are asynchronous so you have to call exec method for create update ect.. on a model
In the end you have :
addVote: function (req, res, next) {
var newVotes = 0;
Nomination.findOne(req.param('id'), function foundNomination(err, nom)
{
if (err)
{
return next(err);
}
nom.votes++;
newVotes = nom.votes;
console.log(newVotes);
Nomination.update(req.param('id'), {
votes : newVotes
}, function (err)
{
if (err)
{
return res.negotiate(err);
}
return res.json({
votes : newVotes
});
});
});
},