Reputation: 503
Hello I am trying to remove nested array object id
from document but it is not getting removed. Although I am getting message "Deleted"
I have a response where the structure is :-
{
"admins": {
"users": [
"5d0364048db4957100f33fea" //<===want to delete this relational id
],
"email": "[email protected]",
"password": "$2a$10$vHyGxX9P.t0/ybKcmIzkc.ZCX18oHaVnvTgJIWA2gTNzJ3TCdXS4a",
"_id": "5d0339d5b4b28b6ddff06802",
"companyName": "GH",
"__v": 0
}
I want to delete users
_id
from the array.
I tried this but it is not getting removed.
router.delete('/userDelete/:uId', checkAuth , (req, res, next) =>{
if(req.userData.role2 === 'admin') {
Admin.findOneAndUpdate({ _id: req.params.userId },{ $pull: { 'admins.users': req.params.uId}})
.exec()
.then(result => {
res.status(200).send(["Deleted"]);
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Didn't get deleted"]);
else
return next(err);
});
Controller is like this :-
var admin = new Admin();
admin.companyName = req.body.companyName;
admin.admins = {
email : req.body.email,
password: req.body.password,
users : []
};
I am stuck here , what changes I must do in my route ?
Upvotes: 1
Views: 92
Reputation: 111
Try marking the '_id' as false in the schema itself for the array. For eg, in your schema, mark '_id' as false like below:
admin: {
type: Object,
users: [{
_id: false
}]
}
.
.
//rest of the schema
Upvotes: 0
Reputation: 3186
The problem is here Admin.findOneAndUpdate({ _id: req.params.userId }
req.params.userId
is undefined, because it does not exist in your path. req.params
object holds only one property, uId
.
So your query does not find any data.
req.params.userId
would have value if your method route had a form like this router.delete('/userDelete/:userId/:uId)
.
So you could add userId in the url of your delete request and access it through req.params
object. The new url should be like this
/userDelete/userId/uId
(e.g.)
userDelete/5d0339d5b4b28b6ddff06802/5d0364048db4957100f33fea
Upvotes: 1
Reputation: 150
try to hard code your id here
Admin.findOneAndUpdate({ _id: req.params.userId },{ $pull: { 'admins.users': "5d0364048db4957100f33fea"}})
If it is working then do
req.params.uId.toString()
Upvotes: 0