Reputation: 1044
I am having trouble understanding how new field:value
objects
are added to mongo
databases.
Say I have the following document
:
var people={'firstname': 'John','surname':'Smith',
'favouritefood':[{'fruit':'apples','drink':'coffee'}]}
how do I add 'vegetable':'broccoli' to 'favourite food' so it looks like this:
{'firstname': 'John','surname':'Smith',
'favouritefood':[{'fruit':'apples','drink':'coffee','vegetable':'broccoli'}]}
If I type:
people.findOneAndUpdate({'firstname':'John'},
{$push {favouritefood: {vegetable:broccoli}}},
{upsert:true})
it gives me this:
{'firstname': 'John','surname':'Smith',
'favouritefood':[{'fruit':'apples','drink':'coffee'},{'vegetable':'broccoli'}]}
and if I try:
people.findOneAndUpdate({'favoritefood':'apples'},
{$push {vegetable:broccoli}}},
{upsert:true})
it says:
'$push' is empty. You must specify a field like so: {$push: {<field>: ...}}
Any help is greatly appreciated!
Upvotes: 1
Views: 1246
Reputation: 907
I think you will be able to update the favouritefood array first object following this syntax
But i suggest you the same that people in the comments, change your structure to one more natural in mongoDB. Consider each category of food as an element of the array not an object field of the first element.
Upvotes: 1