Není možné přímo zvýšit hodnotu v .find
dotaz if labelOptions
je pole objektů. Aby to bylo jednodušší, měli byste změnit labelOptions
zadejte z Array of Objects to Object:
"labelOptions": {
"Bob": 112,
"Billy": 32,
"Joe": 45
};
Zvažte také použití .findByIdAndUpdate
místo .findOneAndUpdate
pokud se dotazujete podle _id
dokumentu . A pak můžete dosáhnout toho, co chcete:
Poll.findByIdAndUpdate(
id,
{$inc: {`labelOptions.${labelOption}`: 1 }},
function(err, document) {
console.log(err);
});
AKTUALIZACE:Pokud jste vytrvalí v používání Array of Objects pro labelOptions
, existuje řešení:
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);
});
});