tl;dr
I struggled with this and came up with a solution. Like you, I was trying to query for a deeply nested object by the _id
, but I kept coming up empty with the results. It wasn't until I did some type checking that I realized the id
value I was getting from my frontend, while directly supplied by mongoose, was in fact a String
and not an Object
.
I realize this question was already partially answered before, but that person's solution didn't work for me, and the comment on the answer tells me you wanted to update the specific image you queried for, which is exactly what I was trying to do.
The solution
In order to select an object from the nested array by the _id
value, first you'll have to install the npm package bson-objectid
and use the provided method to convert your string into an objectId
in your query.
In your terminal:
npm i bson-objectid
In your code:
const ObjectId = require('bson-objectid')
userSchema.findOneAndUpdate(
{ "facebook.id": <user-id>, "images._id": ObjectId(<image-id>) },
{ "$set": { "images.$.main": false } },
{ new: true }, // an extra options parameter that returns the mutated document
(err, user) => {
if (err) {
handleErr(err)
} else {
console.log(user)
// do something with new user info
}
)