Sails.js 增量属性

Sails.js Increment Attribute

我正在使用 Sails.js,并尝试在调用函数时将模型中的属性递增 1。它工作并递增 return JSON 值为 1,但从不保存到数据库,所以当我稍后发出 get 请求时,该值仍然是 0.

函数:

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
      });

    });
},

编辑:

这很奇怪。一定是一些范围界定问题。当我将代码更改为此时,控制台输出 0 然后 1。如果我取出第二个 console.log,它输出 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
        });
    });

},

啊哈!它在 findOne 之前调用 Update 函数。但是为什么,我该如何阻止它呢?

我认为你必须这样做:

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
            });
         }
      });

所有数据库访问都是异步的,因此您必须在模型

上为create update 等调用exec 方法

最后你有:

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
        });
    });
});
},

晚会有点晚了,但我可能有更简单的解决方法。当您将 ++ 放在数字之后时,它会将值加一,但在执行此操作之前它会 returns 该值。如果你想要 nom.votes 的值在它加一之后你需要做的就是把 ++ 放在值之前,然后它将 return 加一后的值,就像这样:

return res.json({
    votes : ++nom.votes
});