最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert string array into object Id array - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 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));

You can also simplify the accepted answer like this :

let objectIdArray = stringObjectIdArray.map(mongoose.Types.ObjectId);
发布评论

评论列表(0)

  1. 暂无评论