nodejs mongodb object id to string

IN nodejs, with mongodb, mongoosejs as orm

I am doing this

I have a model, User

User.findOne({username:'someusername'}).exec(function(err,user){
console.log(user) //this gives full object with something like {_id:234234dfdfg,username:'someusername'}
//but

console.log(user._id) //give undefined.
})

Why? And how to get the _id to string then?

take the underscore out and try again:

console.log(user.id)

Also the value returned from id is already a string, as you can see here https://github.com/LearnBoost/mongoose/issues/548#issuecomment-2245903.

I'm using it this way and it works.

Cheers

I'm using mongojs, and i have this example:

db.users.findOne({'_id': db.ObjectId(user_id)  }, function(err, user) {
   if(err == null && user != null){
      user._id.toHexString(); // I convert the objectId Using toHexString function.
   }
})

I hope this help.

Try this:

user._id.toString()

A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length. You need to convert it to string to show it in console using console.log.

So, you have to do this:

console.log(user._id.toString());

try this: objectId.str;

see doc: http://docs.mongodb.org/manual/reference/object-id/

function encodeToken(token){
    //token must be a string .
    token = typeof token == 'string' ? token : String(token)
}

User.findOne({name: 'elrrrrrrr'}, function(err, it) {
    encodeToken(it._id)
})

In mongoose , the objectId is an object (console.log(typeof it._id)).

I faced same problem and .toString() worked for me. I'm using mongojs driver https://github.com/mafintosh/mongojs. Here was my question

Mongodb find is not working with the Objectid

The result returned by find is an array.

Try this instead:

console.log(user[0]["_id"]);