deleteMany in moongose with first condition same but second condition varies

Viewed 21

I am making a simple api in node js and try to delete multiple document at once.The documents has two field 'name' and 'phone'.The name is same but phone is varies.How to acheive this,suggest me any idea.I have checked my api throug postman and it gives the message

{
    "stringValue": "\"[ 9888889999, 888888 ]\"",
    "valueType": "Array",
    "kind": "Number",
    "value": [
        9888889999,
        888888
    ],
    "path": "phone",
    "reason": {
        "generatedMessage": true,
        "code": "ERR_ASSERTION",
        "actual": false,
        "expected": true,
        "operator": "=="
    },
    "name": "CastError",
    "message": "Cast to Number failed for value \"[ 9888889999, 888888 ]\" (type Array) at path \"phone\" for model \"group\""
}

My code is

router.get('/delete_members',(req,res)=>{
        Group.deleteMany({name:req.body.name,phone:{$in:[req.body.phone]}},(err,doc)=>{
            if(err)
            res.send(err);
            else res.json(doc)
        })
    })

The database document is

_id
62e37c2a9f2011c103402b7d
name
"college group"
phone
9888889999
__v
0
_id
62e37c2a9f2011c103402b7e
name
"Family Group"
phone
888888
__v
0
_id
62e37c2a9f2011c103402b7f
name
"Family Group"
phone
9888889999
__v
0
_id
62e37c5f839bb9c7fb2ed4c8
name
"Family Group"
phone
9888889999
__v
0
_id
62e37c5f839bb9c7fb2ed4c9
name
"Family Group"
phone
9888889999
__v
0
_id
62e37c5f839bb9c7fb2ed4ca
name
"Family Group"
phone
9888889999
__v
0
_id
62e37c5f839bb9c7fb2ed4cb
name
"Family Group"
phone
9888889999
__v
0
_id
62e37c5f839bb9c7fb2ed4cc
name
"Family Group"
phone
9888889999
__v
0

The schema is

const groupSchema=new mongoose.Schema({
    name:String,
    phone:Number
})

postman request

http://localhost:8000/delete_members
{
    "name":"Family Group",
    "phone":[888888,9888889999]
}
1 Answers

It appears you have an array inside array, thats why it brakes.

You have this in the mongodb: [req.body.phone] and you are sending this [888888,9888889999], which at the end creates [[888888,9888889999]].

The $in will try to parse every single item in array, so it takes the first item - the [888888,9888889999] and try to parse it as number.

So all you have to do is {$in:req.body.phone} and maybe you should rename it to phones so it is more clear you are expecting an array of numbers, not single one.

Related