简体   繁体   English

MongoDB-猫鼬$ inc在文档数组内的对象

[英]MongoDB - Mongoose $inc an object inside of an array of a document

So I am trying to update the value of an object inside an array inside a document. 因此,我正在尝试更新文档中数组内部的对象的值。 The Schema for the document looks like this: 该文档的架构如下所示:

var pollSchema = new Schema({
  title: String,
  hash: String,
  answers: [{answer: String, votes: Number}]
});

And this is how my current update code looks like: 这是我当前的更新代码如下所示:

module.exports.updatePoll = function(socket, data){
  var answerss = 'answers.0.votes';

  hash = data.url.match(/\/([^/]*)$/)[1];
  Poll.findOne({'hash' : hash}, function(err, poll){
    if (err) return handleError(err);
    console.log(poll.answers[data.id])
  });
  Poll.update({hash: hash}, {$inc: {'answers.{data.id}.votes': 1}}, function(err, poll){
    if (err) return console.log(err);
    //socket.emit('updatePoll', hash);
  });

Ive tried pasting answerss in it instead of 'answers.{data.id}.votes' and also tried some other things. Ive尝试在其中粘贴answerss ,而不是'answers.{data.id}.votes' ,还尝试了其他一些方法。 It only really works when I directly paste in 'answers.0.votes'. 仅当我直接粘贴“ answers.0.votes”时,它才真正起作用。 And this is a problem because the data.id can be a value of 0 to 10. I have no idea how I would implement this and the other answers on stackoverflow or google did not give much insight on the problem. 这是一个问题,因为data.id的值可以是0到10。我不知道我将如何实现它,而关于stackoverflow或google的其他答案对此问题没有太多的了解。

I hope you can help me. 我希望你能帮助我。 Thanks! 谢谢!

You don't need the initial find from what I can tell. 根据我的判断,您不需要最初的发现。 You can do it all in one update statement. 您可以在一个更新语句中完成所有操作。 You need to match the array element you want to update simply by specifying its index: 您只需指定索引就可以匹配要更新的数组元素:

      var answerKey = 'answers.' + data.id + '.votes';
  var updateJSON = {$inc: {}};
  updateJSON.$inc[answerKey] = 1;
  hash = data.url.match(/\/([^/]*)$/)[1];
  Poll.update({hash: hash}, updateJSON, function(err, poll){
    if (err) return console.log(err);
    //socket.emit('updatePoll', hash);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM