102

IN Node.js, 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?

Wahlstrommm
  • 684
  • 2
  • 7
  • 21
Swati Sharma
  • 1,025
  • 2
  • 7
  • 8

14 Answers14

168

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());
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 2
    Note though that this will only work using mongoose - this is not supported in mongodb. – UpTheCreek Jun 27 '13 at 12:53
  • @UpTheCreek, No, I used it with only MongoDB. I used it [here](https://github.com/IonicaBizau/NodeJS-Beginner-Projects/tree/master/people-information-db). – Ionică Bizău Jun 27 '13 at 13:00
  • Since mongo 2.2 it does something else. See the docs: http://docs.mongodb.org/manual/reference/method/ObjectId.toString/ I guess you must be using and older version of mongodb? – UpTheCreek Jun 27 '13 at 13:11
  • No, I use Mongo 2.4.4 and my project still works. Tested it one minute ago. – Ionică Bizău Jun 27 '13 at 13:15
  • 1
    Can confirm that it does not work with my app using mongodb2.4 and mongoskin (which uses the mongo-native driver). Check by typing (new ObjectId().toString()) in the mongo shell - you get a string, but it's not just the hex string. – UpTheCreek Jun 27 '13 at 13:35
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32498/discussion-between-john--and-upthecreek) – Ionică Bizău Jun 27 '13 at 13:42
30

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
AkerbeltZ
  • 569
  • 1
  • 8
  • 13
23

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.
   }
})
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
19

try this:

objectId.str;

see doc.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
anubiskong
  • 1,733
  • 1
  • 13
  • 6
  • 3
    With a little bit more context this would be the perfect answer. – Mathias Apr 26 '19 at 07:41
  • The linked doc here doesn't mention a `str` property of ObjectId-type objects. It does, however, describe the `ObjectId.toString()` method, which as far as I can tell is the best answer. – Cutler.Sheridan Jul 13 '23 at 18:31
10

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

object._id ? object._id.toHexString():object.toHexString();

This is because object._id exists only if the object is populated, if not the object is an ObjectId

Cédric NICOLAS
  • 1,006
  • 2
  • 12
  • 24
4

When using mongoose .

A representation of the _id is usually in the form (received client side)

{ _id: { _bsontype: 'ObjectID', id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },

As you can see there's a buffer in there. The easiest way to convert it is just doing <obj>.toString() or String(<obj>._id)

So for example

var mongoose = require('mongoose')
mongoose.connect("http://localhost/test")
var personSchema = new mongoose.Schema({ name: String })
var Person = mongoose.model("Person", personSchema)
var guy = new Person({ name: "someguy" })
Person.find().then((people) =>{
  people.forEach(person => {
    console.log(typeof person._id) //outputs object
    typeof person._id == 'string'
      ? null
      : sale._id = String(sale._id)  // all _id s will be converted to strings
  })
}).catch(err=>{ console.log("errored") })
turivishal
  • 34,368
  • 7
  • 36
  • 59
davejoem
  • 4,902
  • 4
  • 22
  • 31
2
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)).

elrrrrrrr
  • 894
  • 8
  • 15
2

starting from Mongoose 5.4, you can convert ObjectId to String using SchemaType Getters.

see What's New in Mongoose 5.4: Global SchemaType Configuration.

BaDr Amer
  • 820
  • 11
  • 29
0

The result returned by find is an array.

Try this instead:

console.log(user[0]["_id"]);
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Access the property within the object id like that user._id.$oid.

DanielKhan
  • 1,190
  • 1
  • 9
  • 18
0

Really simple use String(user._id.$oid)

0

try this : console.log(user._doc._id)

isi.kacer
  • 76
  • 6
0

None of the above was working for me. I had to use

import { ObjectID } from 'bson';

(id as unknown as ObjectID).toString('hex');

In typescript

Tom
  • 111
  • 1
  • 8
0

There are multiple approaches to achieve it ...

objectId.toString()

Using String Constructor

String(objectId)

Using Template Literals

const stringId = `${objectId}`;

Using Concatenation

const stringId = '' + objectId;

Using JSON.stringify

const stringId = JSON.stringify(objectId);