Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But it gives me the following error:

"message": "Cast to ObjectId failed for value \"[\n  new 
ObjectId(\"63bd7878f1f085f7d8a6827f\"),\n  new
ObjectId(\"63be730bf1f085f7d8a682c8\")\n]\" 
(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: ids.map(e => mongoose.Types.ObjectId(e)) } }
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading