2016-12-10 5 views
0

の配列内の値をインクリメント私はPollスキーマに基づいて、この文書を持っ例えば配列マングース - オブジェクト

内のオブジェクトの値をインクリメントする方法を考え出す苦労しています:

{ 
    "_id": "584b2cc6817758118e9557d8", 
    "title": "Number of Skittles", 
    "description": "Test1", 
    "date": "Dec 9, 2016", 
    "__v": 0, 
    "labelOptions": [ 
    { 
     "Bob": 112 
    }, 
    { 
     "Billy": 32 
    }, 
    { 
     "Joe": 45 
    } 
    ] 
} 

急行使用して、私ははるかにこれを取得することができています:labelOption私はその値をインクリメントしたいものです

app.put('/polls/:id', function(req, res){ 
    let id = req.params.id; 
    let labelOption = req.query.labelOption; 
    Poll.findOneAndUpdate(
    {'_id' : id}, 
    {$inc: {`labelOptions.$.${labelOption}`: 1 }}, 
    function(err){ 
     console.log(err) 
    }) 

さらに簡潔にするため、ドキュメント内を横断する際に問題が発生しています。

答えて

2

labelOptionsがオブジェクトの配列の場合、.findクエリの値を直接インクリメントすることはできません。それを容易にするには、オブジェクトにオブジェクトの配列からlabelOptionsタイプを変更する必要があります:あなたは、ドキュメントの_idによって照会されている場合

"labelOptions": { 
    "Bob": 112, 
    "Billy": 32, 
    "Joe": 45 
}; 

.findByIdAndUpdateの使用を検討して代わりに .findOneAndUpdate

Poll.findByIdAndUpdate(
    id, 
    {$inc: {`labelOptions.${labelOption}`: 1 }}, 
    function(err, document) { 
    console.log(err); 
}); 

UPDATE:そして、あなたはあなたがで欲しいものを達成することができます

Poll.findById(
    id, 
    function (err, _poll) { 

     /** Temporarily store labelOptions in a new variable because we cannot directly modify the document */ 
     let _updatedLabelOptions = _poll.labelOptions; 

     /** We need to iterate over the labelOptions array to check where Bob is */ 
     _updatedLabelOptions.forEach(function (_label) { 

      /** Iterate over key,value of the current object */ 
      for (let _name in _label) { 

       /** Make sure that the object really has a property _name */ 
       if (_label.hasOwnProperty(_name)) { 

        /** If name matches the person we want to increment, update it's value */ 
        if (_name === labelOption) ++_label._name; 
       } 
      } 
     }); 

     /** Update the documents labelOptions property with the temporary one we've created */ 
     _poll.update({labelOptions: _updatedLabelOptions}, function (err) { 

      console.log(err); 
     }); 
    }); 
:あなたは labelOptionsのためのオブジェクトの配列を使用して、上に永続化されている場合、回避策はあり