简体   繁体   中英

How to add ObjectId in array all elements in mongodb using nodejs?

I am using Mongodb and nodejs. I have stored array values in variable.below like this.

tag = ["58622e3bf39d570b21ece1b3", "58622e3bf39d570b21ece1a2", "58622e3bf39d570b21ece1r3"]

when i stored tag in mongodb database, I need to convert like this below.

tag = [ObjectId("58622e3bf39d570b21ece1b3"), ObjectId("58622e3bf39d570b21ece1a2"), ObjectId("58622e3bf39d570b21ece1r3")]

using nodejs, how to add objectId to array/list. without mongoose. is it possible?

Assuming your using the node js MongoDB driver, you can use the ObjectID method. This will return an object instance of ObjectID. Use map and pass the function in.

const ObjectID = require('mongodb').ObjectID;

const objectIds = tag.map(ObjectID);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM