2016-12-10 2 views
0

ich harte Zeit, herauszufinden habe, wie innerhalb eines ArraysMungo - Erhöhe Wert innerhalb eines Arrays von Objekten

Zum Beispiel einen Wert in einem Objekt zu erhöhen Ich habe dieses Dokument basiert auf Poll Schema:

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

Mit Express, ich bin diese in der Lage weit zu kommen:

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

wo labelOption derjenige ist, ich mag würde seinen Wert erhöhen

Um präziser zu sein, habe ich Schwierigkeiten, innerhalb des Dokuments zu transversieren.

Antwort

2

Es ist nicht möglich, den Wert in der .find Abfrage direkt zu erhöhen, wenn labelOptions ein Objekt-Array ist. Um dies zu erleichtern, sollten Sie den labelOptions Typ verändern von Array von Objekten an diesem Objekt

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

Sehen Sie sich auch .findByIdAndUpdate statt .findOneAndUpdate verwenden, wenn Sie durch das Dokument des _id abfragen. Und dann können Sie erreichen, was Sie wollen von:

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

UPDATE: Wenn Sie sich mit Array von Objekten für labelOptions persistent sind, gibt es eine Abhilfe:

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