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!
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!
Share Improve this question asked Jun 22, 2018 at 2:59 KevinVuDKevinVuD 6112 gold badges7 silver badges27 bronze badges2 Answers
Reset to default 18Use 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));
You can also simplify the accepted answer like this :
let objectIdArray = stringObjectIdArray.map(mongoose.Types.ObjectId);