javascript - Sails.js Increment Attribute -
i'm using sails.js, , trying increment attribute in model 1 when function called. works , increments , return json value 1, never saves database, when make request later, value 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 weird. must scoping issue. when change code this, console outputs 0 1. if take out second console.log, 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 update function before findone. why, , how stop it?
i think have :
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 asynchronous have call exec
method create
update
ect.. on model
in end 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 }); }); }); },
Comments
Post a Comment