Shaishab Roy
Shaishab Roy

Reputation: 16805

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"
}

Upvotes: 2

Views: 2571

Answers (2)

Edwin
Edwin

Reputation: 440

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
  }

Upvotes: 2

rodamn
rodamn

Reputation: 2211

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();

Upvotes: 1

Related Questions