2

I am using MongoDB native driver for NodeJS, and am having trouble converting ObjectID to a string.

My code looks like:

db.collection('user', function(err, collection) {
  collection.insert(data, {safe:true}, function(err, result) { 
    var myid = result._id.toString();
    console.log(myid);
  )};
});

I have tried various suggestions on StackOverflow like:

myid = result._id.toString();
myid = result._id.toHexString();

but none of them seemed to work.

I am trying to convert the ObjectID to base64 encoding.

Not sure if I am running into supported functionality under the Mongo native driver.

2 Answers 2

7

This work for me:

var ObjectID = require('mongodb').ObjectID;
var idString = '4e4e1638c85e808431000003';
var idObj = new ObjectID(idString);

console.log(idObj);
console.log(idObj.toString());
console.log(idObj.toHexString());

Output:

4e4e1638c85e808431000003
4e4e1638c85e808431000003
4e4e1638c85e808431000003
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, both of these examples have been very helpful
2

insert returns an array of results (as you can also send an array of objects to be inserted), so your code is trying to get the _id from the array instance rather than the first result:

MongoClient.connect("mongodb://localhost:27017/testdb", function(err, db) {
    db.collection("user").insert({name:'wiredprairie'}, function(err, result) {
        if (result && result.length > 0) {
            var myid = result[0]._id.toString();
            console.log(myid);
        }
    });
});

Also, you won't need to base64 encode the result of calling toString on an ObjectId as it's returned as a hex number already. You could also call: result[0]._id.toHexString() to get the Hex value directly (toString just wraps toHexString).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.