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!
Use Array.prototype.map()
to invoke the method on every element of the array and collect the results into a new array:
let objectIdArray = stringObjectIdArray.map(s => mongoose.Types.ObjectId(s));
You can also simplify the accepted answer like this :
let objectIdArray = stringObjectIdArray.map(mongoose.Types.ObjectId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With