简体   繁体   中英

How to convert _bsontype objectID value to string/objectID to insert in mongoDB using node.js

I have a JSON file that contains object like bellow.

{
    userID: {"_bsontype":"ObjectID","id":{"0":92,"1":237,"2":216,"3":42,"4":254,"5":178,"6":68,"7":182,"8":208,"9":254,"10":51,"11":64}},
    userName: "abc"
}

Note : Also have some nested fields like userID.

when trying to import to MongoDB using bulk insert getting error

UnhandledPromiseRejectionWarning: Error: object [{"_bsontype":"ObjectID","id":{"0":92,"1":237,"2":216,"3":42,"4":254,"5":178,"6":68,"7":182,"8":208,"9":254,"10":51,"11":64}}] is not a valid ObjectId

How can I convert userID to objectID/string? like ObjectId("5d1de1bab90f8bf15f58df3f") or "5d1de1bab90f8bf15f58df3f"

The expected output in DB:

{
    userID: ObjectId("5d1de1bab90f8bf15f58df3f"),
    userName: "abc"
}

or

{
    userID: "5d1de1bab90f8bf15f58df3f",
    userName: "abc"
}

Thank you rodamn,

You have put me on the right track. Just for the sake of it. This is my utility function. Verbose but it works.

 const { ObjectID } = require( 'mongodb' ) toObjectID: function ( object ) { let hexString = '' Object.values(object.id).forEach(elem =>{ const result = elem.toString(16) if(result.length === 2) { hexString += result } else { hexString += "0" + result } }) const id = new ObjectID(hexString) return id }

I had a similar situation with ObjectID insertion that I was able to resolve. These steps -- though seeminly round-about for the situation -- would accomplish the goal:

1 . Convert the id from array of base10 ints to string of base16 characters:

const idString = obj.userID.id.map(num => {
  var result = num.toString(16);
  return result.length == 2 ? num : "0" + num;
})
.join('');

2 . Create an Object ID from string:

const _id = ObjectID(idString);

3 . Convert back to string Convert from an ObjectID back to the ObjectID() form that mongodb expects when inserting or updating documents:

_id.toString();

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