How do I push to the inner arrays in MongoDB?
[
{ emoji1: ['user19', 'user20', 'user21']},
{ emoji5: ['user12', 'user13', 'user14']},
{ emoji9: ['user29', 'user30', 'user34']}
]
I tried:
await Post
.updateOne({ _id: postID }, {
$push: {
[`reactions[0].emoji1`]: 'random user'
}
})
...where Post is my Mongoose Schema and "reactions" is the array above. I think I am doing something wrong in $push.
The result should be:
[
{ emoji1: ['user19', 'user20', 'user21', 'random user']},
{ emoji5: ['user12', 'user13', 'user14']},
{ emoji9: ['user29', 'user30', 'user34']}
]
Thanks in advance!
CodePudding user response:
You can use this query:
db.collection.update({
id: 1,
"reactions.emoji1": {
"$exists": true
}
},
{
"$push": {
"reactions.$.emoji1": "random user"
}
})
Example here