MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Mongoose - Incrémente une valeur dans un tableau d'objets

Il n'est pas possible d'incrémenter directement la valeur dans le .find requête si labelOptions est un tableau d'objets. Pour vous faciliter la tâche, vous devez modifier les labelOptions tapez de Tableau d'Objets à Objet :

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

Pensez également à utiliser .findByIdAndUpdate au lieu de .findOneAndUpdate si vous interrogez par le _id du document . Et ensuite, vous pouvez obtenir ce que vous voulez en :

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

MISE À JOUR :Si vous persistez à utiliser un tableau d'objets pour labelOptions , il existe une solution :

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