1

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: [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\""
1
  • 1
    [ids.map(e => mongoose.Types.ObjectId(e))] -> ids.map(e => mongoose.Types.ObjectId(e)) because .map() returns an array, you don't need to wrap it in another array. Commented Jan 11, 2023 at 10:15

2 Answers 2

1

You have added extra brackets at $in query, try this...

const affectedUsers = await Users.find(
  { _id: { $in: ids.map(e => mongoose.Types.ObjectId(e)) } }
);
Sign up to request clarification or add additional context in comments.

Comments

0

You should remove the extra array in the $in operator, like so:

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

Comments

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.