Reputation: 31
I want to update "displayTitle" to "12345" where objectId is "5d8c8f4a4449a851f6kkk6o2" under "title" of topten= "under 50000" findOneAndUpdate for nested object elements of an array with two conditions, first for selecting the specific document and the second one to find the specific object in the nested array. Collection Name is : topten.
> db.topten.find().pretty();
{
"_id" : ObjectId("5d8c8f254449a851f6aaa6r3"),
"title" : "under 50000",
"products" : [
{
"_id" : ObjectId("5d8c8f4a4449a851f6kkk6o2"),
"productId" : "5cfe541ae759d9699b5213542",
"displayTitle" : "dhtyks",
"score" : 100,
"priority" : 50,
"description" : "Upcoming"
},
{
"_id" : ObjectId("5d8c8f8f4449a86544646"),
"productId" : "5cfe512bca044365efsdfgg45",
"displayTitle" : "Spice",
"score" : 10,
"priority" : 800,
"description" : "Advanced"
}
],
"created" : ISODate("2019-09-26T10:12:53.804Z"),
"updated" : ISODate("2019-10-03T05:24:19.296Z"),
"slug" : "under-10000",
"__v" : 0
{
"_id" : ObjectId("5d8c8f254449a851f6ddd9a1"),
"title" : "under 10000",
"products" : [
{
"_id" : ObjectId("5d8c8f4a4449a851f6ddd9a2"),
"productId" : "5cfe541ae759d9699b56759b",
"displayTitle" : "ABCDEF6",
"score" : 10,
"priority" : 200,
"description" : "New Gen"
},
{
"_id" : ObjectId("5d8c8f8f4449a851f6ddd9a4"),
"productId" : "5cfe512bca044365ef1dcd0f",
"displayTitle" : "Micromax",
"score" : 1,
"priority" : 200,
"description" : "Upcoming"
}
],
"created" : ISODate("2019-09-26T10:12:53.804Z"),
"updated" : ISODate("2019-10-03T05:24:19.296Z"),
"slug" : "under-10000",
"__v" : 0
Code I am using for it is:
topten.findOneAndUpdate({"title" : "under 50000", "products": { $elemMatch: { "_id": "5d8c8f4a4449a851f6kkk6o2" } }},
{"products.0.displayTitle":"12345"},
function (err, doc) {
if (err) {
console.log(err);
reject(new Error(err));
return;
} else {
console.log('AAAAAAAAAAAAAAAAAAAAAAAA', doc)
res.status(200)
.json({
success: true,
msg: 'Attached product updated succesfully`);'
})
}
}
)
Query is running but its not updating the value in my Db. Please help, I am stuck here.
Upvotes: 3
Views: 521
Reputation: 582
Try using a $set where you are assigning products.0.displayTitle like so:
topten.findOneAndUpdate(
{"title" : "under 50000",
"products": { $elemMatch: { "_id": "5d8c8f4a4449a851f6kkk6o2" } }},
{$set: { products.0.displayTitle: "12345"}},
function (err, doc) {
if (err) {
console.log(err);
reject(new Error(err));
return;
} else {
console.log('AAAAAAAAAAAAAAAAAAAAAAAA', doc)
res.status(200)
.json({
success: true,
msg: 'Attached product updated succesfully`);'
})
}
}
)
Upvotes: 2