如何通过字段查找并将数量添加到mongoose中的另一个字段

时间:2015-03-29 03:27:34

标签: node.js mongodb mongoose

我有PlayerModel,看起来像(使用mongoose / mongo)

var PlayerModel = new Schema({
    playerUUID : String,
    score : Number
});

我想添加20分,以playerUUID "1261236237621"分数。 如何查找和更新PlayerModel?可以在一个语句中以sql更新吗?

1 个答案:

答案 0 :(得分:1)

首先使用您想要的PlayerModel找到playerUUID,然后更新它,例如:

var PlayerModel = new Schema({
  playerUUID : String,
  score : Number
});

var Player = mongoose.model('Player', PlayerModel);

Player.findOne({ playerUUID: "1261236237621" }, function (err, player) {

  if (err) throw new Error(err);
  player.score += 20;
  player.save(function (err, playerResponse) {

    if (err) throw new Error(err);
    // playerResponse is your updated Player
    console.log(playerResponse);
  });
});