Here is my mongo collection's sample:
{
"data": {
"categories": [
{
"categoryName":"Nature",
"urls": [
{
"name":"mountain",
"url":"mountain-url"
}
]
},
{
"categoryName":"Animals"
"urls": [
{
"name":"lion",
"url":"lion-url"
}
]
}
]
}
}
I want to push an object to urls array of Nature category. I tried this:
collection.updateOne({"categories.$.categoryName":"Nature"},{$push:{"categories.$.urls":object}},(err, result) => {
if (err) throw err;
console.log('Successful');
});
It returns 'Successful' but nothing change in MongoDB. How can i do this ?
CodePudding user response:
I found solution of my problem. Here is update code:
collection.updateOne({"data.categories.categoryName":"Nature"},{$push:{"data.categories.$.urls":object}},(err, result) => {
if (err) throw err;
console.log('Successful');
});
CodePudding user response:
Use $set instead of $push
Try this -
collection.updateOne({"data.categories.categoryName":"Nature"},{$set:{"data.categories.urls":object}},(err, result) => {
if (err) throw err;
console.log('Successful');
});