Mongoose:如何将字段/值插入到现有的子文档中

我无法理解如何将新field:value objects添加到mongo数据库。

说我有以下document

 var people={'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee'}]} 

如何添加“蔬菜”:“西兰花”,以“最喜爱的食物”,所以它看起来像这样:

 {'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee','vegetable':'broccoli'}]} 

如果我input:

 people.findOneAndUpdate({'firstname':'John'}, {$push {favouritefood: {vegetable:broccoli}}}, {upsert:true}) 

它给了我这个:

 {'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee'},{'vegetable':'broccoli'}]} 

如果我尝试:

 people.findOneAndUpdate({'favoritefood':'apples'}, {$push {vegetable:broccoli}}}, {upsert:true}) 

它说:

 '$push' is empty. You must specify a field like so: {$push: {<field>: ...}} 

任何帮助是极大的赞赏!

我认为你可以按照这个语法更新favouritefood数组的第一个对象

但是我build议你和评论中的人一样,把你的结构改成mongoDB中更自然的一个。 考虑每一类食物作为数组的一个元素而不是第一个元素的对象字段。