Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 546
Swati Sharma Avatar asked Oct 27 '12 22:10

Swati Sharma


2 Answers

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()); 
like image 77
Ionică Bizău Avatar answered Oct 04 '22 01:10

Ionică Bizău


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.

like image 40
AkerbeltZ Avatar answered Oct 04 '22 02:10

AkerbeltZ