Javascript Mongoose-在对象数组中增加一个值
我很难弄清楚如何在数组中增加对象的值 例如,我有一个基于Javascript Mongoose-在对象数组中增加一个值,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我很难弄清楚如何在数组中增加对象的值 例如,我有一个基于Pollschema的文档: { "_id": "584b2cc6817758118e9557d8", "title": "Number of Skittles", "description": "Test1", "date": "Dec 9, 2016", "__v": 0, "labelOptions": [ { "Bob": 112 }, { "Billy": 3
Poll
schema的文档:
{
"_id": "584b2cc6817758118e9557d8",
"title": "Number of Skittles",
"description": "Test1",
"date": "Dec 9, 2016",
"__v": 0,
"labelOptions": [
{
"Bob": 112
},
{
"Billy": 32
},
{
"Joe": 45
}
]
}
使用express,我能够做到这一点:
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)
})
其中,labelOption
是我希望增加其值的选项
更简洁地说,我在文档内部横切时遇到问题。无法直接增加
中的值。如果labelOptions
是对象数组,则查找查询。为了简化操作,您应该将标签选项
类型从对象数组更改为对象:
"labelOptions": {
"Bob": 112,
"Billy": 32,
"Joe": 45
};
也可以考虑使用<代码> .FIDBIDIDANDUPDATE 而不是<代码> .FIDONAND UPDATE <代码>。然后,你可以通过以下方式实现你想要的:
Poll.findByIdAndUpdate(
id,
{$inc: {`labelOptions.${labelOption}`: 1 }},
function(err, document) {
console.log(err);
});
更新:如果您坚持使用对象数组作为标签选项
,有一个解决方法:
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);
});
});
还有另一种方法可以做到这一点,它允许更灵活的文档模型。如果向对象添加字段,如:
{
"_id": "584b2cc6817758118e9557d8",
"title": "Number of Skittles",
"description": "Test1",
"date": "Dec 9, 2016",
"__v": 0,
"labelOptions": [
{
"name": "Bob",
"number": 112
},
{
"name": "Billy",
"number": 32
},
{
"name": "Joe"
"number": 45
}
]
}
然后你可以做:
app.put('/polls/:id', function(req, res){
let id = req.params.id;
let labelOption = req.query.labelOption;
Poll.findOneAndUpdate(
{
'_id' : id,
'labelOptions.name
},
{$inc: {
`labelOptions.$.number`: 1
}},
function(err){
console.log(err)
})