CastError: Cast to string failed for { in: [ ...] }

Hi, I’m working on a project where I need to be able to pull the objects containing certain userIds from an array of objects:

{
_id: "63492520b5ef3f0bf00282ca",
users: [ {
_id:"64d6c6cd2b758fd95dceeedd"
userId: "AB211C5F-9EC9-429F-9466-B9382FF61035"
},{
_id:"64d6cccd2b818fd95ccefedd"
userId: "AC412D5H-8GE6-631R-8581-C1452JF60029"
}]

I’ve been trying to do this with versions of:

 const pullUsers= await Subscribed.updateOne({_id:user._id},
  {$pull: {
    "users": {
    "userId":{in:[...input.pullUsers]}
    }
  }},);

where input.pullUsers is:

input {
  pullUsers: [ 'AB211C5F-9EC9-429F-9466-B9382FF61035' ]
}

but I keep getting an error: "message": "Cast to string failed for value \"{ in: [ 'AB211C5F-9EC9-429F-9466-B9382FF61035' ] }\" (type Object) at path \"userId\"", which I don’t understand because pullUsers is a string and so is userId. I’ve tried:

    let pulledUsers = [];
    for (let i=0; i<input.pullUsers?.length; i++){
    const data = input.pullUsers[i].toString()
    pulledUsers.push(data)
  }

const pullUsers= await Subscribed.updateOne({_id:user._id},
  {$pull: {
    "users": {
    "userId":{in:[pulledUsers]}
    }
  }},);

to double check that my input would be sending strings to be pulled from mongodb, but I’m getting the same error. I’ve also tried looking at other instances of castErrors that people have had, but I couldn’t find one that would helped me with this issue. If anyone knows why this might be happening, I would really appreciate any help or advice. Thank you!

Hello @p_p1,

Are you using Mongoose NPM, if yes then can you show your schema declaration? might be the type of the userId is different than your input value.

If not then,

Can you try a static value in your query as below, if it is working then there is some issue in your input variables,

const pullUsers= await Subscribed.updateOne(
  { _id: "63492520b5ef3f0bf00282ca" },
  {
    $pull: {
      users: {
        userId: { $in: ["AB211C5F-9EC9-429F-9466-B9382FF61035"] }
      }
    }
  }
)

As you can see the query is working here,

1 Like

Hi Vishal,

Thank you for your response! I tried the static version that you gave me, and it worked, so like you mentioned it must be something with my input variables, but I have no idea what it could be. I’m using graphql and I have: pullUserInput {pullUsers: [String]} (this is equal to the input variable), so my backend should be getting an array of strings, but for some reason it’s not registering that.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.