Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string array into object Id array

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!

like image 925
KevinVuD Avatar asked Jun 22 '18 02:06

KevinVuD


2 Answers

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));
like image 121
Robby Cornelissen Avatar answered Nov 10 '22 03:11

Robby Cornelissen


You can also simplify the accepted answer like this :

let objectIdArray = stringObjectIdArray.map(mongoose.Types.ObjectId);
like image 31
Allaoua Benchikh Avatar answered Nov 10 '22 04:11

Allaoua Benchikh