sql >> Base de Datos >  >> NoSQL >> MongoDB

Mongoose:incrementa un valor dentro de una matriz de objetos

No es posible incrementar directamente el valor en .find consulta si labelOptions es una matriz de objetos. Para hacerlo más fácil, debe cambiar las labelOptions tipo de matriz de objetos a objeto:

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

También considere usar .findByIdAndUpdate en lugar de .findOneAndUpdate si está consultando por el _id del documento . Y luego, puede lograr lo que desea al:

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

ACTUALIZACIÓN:si persiste en usar Array of Objects para labelOptions , hay una solución alternativa:

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