'I cannot remove a subdocment in mongo Db?
I am trying to delete a subdocument from my users collection in Mongo Db, my best attempt to remove the subdocument is the the route below. However is does not work. I have been able to $unset the entire Favorite Movies array but I only want to delete one Item by its _id within the Favorite Movies Sub-Document. What am I doing Wrong.
// My Route That is supposed to Delete a Subdocument:
app.put('/Favorites/:UserName/delete/:_id',passport.authenticate('jwt', { session: false }), (req, res) => {
users.findOneAndUpdate({ UserName: req.params.UserName })
.then((user) => {
if (!user) {
res.status(400).send('ID: ' + req.params._id + ' was not found!!');
} else {
user.updateOne(
{UserName: req.params.UserName},
{
$pull: {
"FavoriteMovies": {
"ObjectId": req.params._id
}
}
})
res.status(200).send('ID: ' + req.params._id + ' was deleted!');
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
//Mongoose Model Schema for User in which the Subdocuemnt I want to delete is in Favorite Movies:
let usersSchema = mongoose.Schema({
_id: {type: Object},
UserName: {type: String, required: true},
Password: {type: String, required: true},
Email: {type: String, required: true},
Birthday: Date,
FavoriteMovies:{type: Object},
ImagePath: String
});
The User Object with Favorite Movies Subdocument in Postman- Raw:
[
{
"_id": 1650119097711,
"UserName": "robbies",
"Password": "$2b$10$UZmRBLZF0UGWrB1OrZVI2ePc7N1ae5sSZj0RlSU8WyRIRsfdE.yYW",
"Email": "[email protected]",
"Birthday": "1988-05-05T00:00:00.000Z",
"FavoriteMovies": [
{
"ObjectId": 2009,
"Title": "The NoteBook",
"Genre": "Romance"
},
{
"ObjectId": 2001,
"Title": "Hacksaw Ridge",
"Genre": "Action"
}
],
"ImagePath": null,
"__v": 0
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
