Reputation: 5039
I have this query
router.delete('/:_id', async (req, res) => {
const {_id} = req.params;
const errors = [];
console.log(_id);
await Promise.all([
// Pon.findOneAndDelete({_id}).catch((e) => {
// console.log(e);
// errors.push('Something went wrong. Pon was not deleted');
// }),
// ^^^^^^^^^ this part worked. Wanted to just test the other query
User.findOneAndUpdate({_id: req.user._id}, {$pull: {pons: {_id}}}).catch((e) => {
console.log(1, e);
errors.push('Something went wrong. Pon reference was not deleted from user');
}),
]);
if (errors.length > 0) {
console.log(2, errors);
res.json({ok: false, errors});
} else {
res.json({ok: true});
}
});
I am just trying to remove an element from user object. Here's the object
{
"_id": {
"$oid": "5ea2d8cffe35b93e84f7962b"
},
"pons": [
{
"$oid": "5ea98b181a2be04ec87aa710" // this is what I want to remove
}
],
"email": "[email protected]",
"password": "$2a$12$VJ0MkcGUs42pikT42qLpyOb0Sd53j9LXH8dY9RdR/GcmUVzJoP8gi",
"__v": 0
}
This query doesn't throw any errors, catch doesn't catch anything, so I don't know what I'm doing wrong. I tried just doing {pons: _id}
instead of {pons: {_id}}
but no luck.
The _id
is correct. Checked with console.log.
What am I missing?
Upvotes: 0
Views: 61
Reputation: 5245
_id
is just a String
. If you want to match an ObjectId
, you have to wrap it like this mongoose.Types.ObjectId(_id)
const ObjectId = mongoose.Types.ObjectId
User.findOneAndUpdate(
{ _id: ObjectId(req.user._id) },
{ $pull: { pons: ObjectId(_id) } }
)
Since you are querying by _id
, you could also use User.findByIdAndUpdate()
which will wrap req.user._id
with ObjectId
for you.
const ObjectId = mongoose.Types.ObjectId
User.findByIdAndUpdate(req.user._id, { $pull: { pons: ObjectId(_id) } })
Upvotes: 2