在MongoDB中更新一个数组

对于下面的结构,我正在尝试更新选项下的第一个数组项目[“milk”,1]:

{ options:[["milk", 0], ["chocolate", 0], ["others", 0]], timestamp:"2017-09-26T14:42:49.359Z" title:"shopping list" username:"a" } 

这是我使用的mongoose片段。

 router.put('/',(req,res) => { let {_id, value, option} = req.body; eventModel.findOneAndUpdate( {_id:_id, options: [option, value]}, { $set: {"options.$": [option, value + 1]}}, function(err){ if(err){ res.status(400).json({ error: err }); } console.log("event updated"); }); }); 

我总是得到“事件更新”,没有任何错误,但项目没有得到更新,任何帮助表示赞赏。 谢谢

为什么使用这种数组对来存储你的值? 任何具体的原因。

否则,您可以像这样存储数据,然后查询:

 const ShoppingListSchema = new Schema({ username: {type: String}, title: {type: String}, timestamp: {type: Date, default: Date.now()}, options: [{ product: {type: String}, selected: {type: Number} }] }); // then eventModel.findOneAndUpdate( {_id:_id, 'options.product': productName, 'options.selected': selected}, {"options.$.value": value + 1}, function(err){ if(err){ res.status(400).json({ error: err }); } console.log("event updated"); }); 

//还有,快速logging。 如果你想在你的列表中设置项目为“包含”或不,那么你实际上不需要“值”部分。 产品在购物清单中,如果它在数组中。

 options: ["milk", "bread", "beer"] would work just as well 

另外,我可以看到你正在做的“值+ 1”只是一个快速的说明,有一个操作数递增值:

 $inc: {field: value} 

使用其他选项快速更新:

 db.getCollection('list').update({"options": ["milk", 0]}, {$set: {"options.$.1": 1} }) use $.1 to refer to the second element in your array, which is the number.