12

I have an array of string

let stringObjectIdArray = ['fssdlfsd343','43434234242','342424242']

and I want to change the string array into an object Id array by using mongoose type but it didn't work. It only works for a string not array type.

let objectIdArray = mongoose.Types.ObjectId(stringObjectIdArray)
// above will give error

Is there a way to help me in this case? Thank you very much for helping me!

2 Answers 2

18

Use Array.prototype.map() to invoke the method on every element of the array and collect the results into a new array:

const objectIdArray = stringObjectIdArray.map(s => new mongoose.Types.ObjectId(s));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!
better add "new" before the ObjectId class
1

You can also simplify the accepted answer like this :

let objectIdArray = stringObjectIdArray.map(mongoose.Types.ObjectId);

1 Comment

depends on the node version and configuration, you might get this error: TypeError: Class constructor ObjectId cannot be invoked without 'new'

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.