1

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 ?

EDIT:- DB is like this DB

6
  • console this result Commented Jun 17, 2019 at 11:36
  • @mehta-rohan getting null Commented Jun 17, 2019 at 11:43
  • that means your query to search the record is not working Commented Jun 17, 2019 at 12:12
  • i dont see any param userId. The only param i see is uId Commented Jun 17, 2019 at 12:13
  • @mehta-rohan yes, i got that , but I am unable to find the solution Commented Jun 17, 2019 at 12:13

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

7 Comments

This is deleting my document.
No, it does not delete any document. Did you try it?
I updated my answer to help you understand better your problem. Change the url in your client side.
Yes i did the same .. its is deleting entire object
console.log(req.params.userId) and console.log(req.params.uId) and check the output if it is ok
|
0

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()

6 Comments

Didn't worked even after hard coded. Showing "Deleted" message but it is still there in the array
How will I query { _id: req.params.userId} for the company , it is coming undefined. And also when I am consoling result, it is null
let me know hows is your user array looks like it it contains only strings then it will work, but if id's are stored in that way ObjectId("5ca5b052627cd94863a25b32") then you should use this var ObjectId = require('mongodb').ObjectID; { _id: ObjectId (req.params.userId)}
Like this db.getCollection('testing').update({_id:ObjectId("5d0765c44cacc6168afe7b42")}, {$pull:{"admins.users":"5ca5b0fa627cd94863a25b70"}} )
then you should use ObjectId which is imported in the previous comments Admin.update({ _id: ObjectId(req.params.userId) },{ $pull: { 'admins.users': ObjectId(req.params.uId)}})
|
0

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

5 Comments

Why I should make it false ?
This would remove the _id from the nested array, and would return the result which you’re expecting.
Actually I am pushing only _id in the array. So if I make it false, nothing will get push. Remove from here I want to delete in an operation. Thanks I didn't knew this. Now everything is working.
If this has resolved your issue, would you mind accepting and upvoting the answer?
I have already solved by dimitris tseggenes's way. You solution will not push the _id. I need to push and delete. Thanks bdw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.