Arcane
Arcane

Reputation: 117

NodeJS, using MongoDB Native driver, how do I convert ObjectID to string

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.

Upvotes: 2

Views: 3104

Answers (2)

accurate respondetur
accurate respondetur

Reputation: 702

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

Upvotes: 7

WiredPrairie
WiredPrairie

Reputation: 59793

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).

Upvotes: 2

Related Questions