How do I turn list of strings to list of ObjectIds in Node JS?


I’m using mongoose and I have the following list:

const ids: ["63bd7878f1f085f7d8a6827f", "63be730bf1f085f7d8a682c8"];

I want to turn ids into a list of ObjectIds..

I’ve tried the following:

const affectedUsers = await Users.find(
            { _id: { $in: [ => mongoose.Types.ObjectId(e))] } }

But it gives me the following error:

"message": "Cast to ObjectId failed for value \"[\n  new 
ObjectId(\"63bd7878f1f085f7d8a6827f\"),\n  new
(type Array) at path \"_id\" for model \"users\""

>Solution :

you have added extra brackets at $in query, try this…

const affectedUsers = await Users.find(
        { _id: { $in: => mongoose.Types.ObjectId(e)) } }

Leave a Reply Cancel reply