109

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?

3
  • 1
    Please note that the answers using .toString() will only work with mongoose, not any of the native mongodb drivers (as per 2.2, where you must use .toHexString() Commented Jun 27, 2013 at 12:57
  • 1
    .toString() worked for me using mongojs driver as well Commented Dec 29, 2014 at 22:42
  • docs.mongodb.com/manual/reference/method/ObjectId.toString Commented Dec 22, 2016 at 13:35

14 Answers 14

178

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());
Sign up to request clarification or add additional context in comments.

6 Comments

Note though that this will only work using mongoose - this is not supported in mongodb.
@UpTheCreek, No, I used it with only MongoDB. I used it here.
Since mongo 2.2 it does something else. See the docs: docs.mongodb.org/manual/reference/method/ObjectId.toString I guess you must be using and older version of mongodb?
No, I use Mongo 2.4.4 and my project still works. Tested it one minute ago.
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.
|
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.

2 Comments

I just want to note that this does not work for [email protected].
Ha I just posted the same thing below @writofmandamus its working fine for me on 5.4.19
24

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

Comments

19

try this:

objectId.str;

see doc.

2 Comments

With a little bit more context this would be the perfect answer.
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.
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

Comments

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") })

1 Comment

I don't think so. That was what return to me [object Object]
3

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.

Comments

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

Comments

1

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

Comments

0

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

Comments

0

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

Comments

0

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

Comments

0

The result returned by find is an array.

Try this instead:

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

3 Comments

That would be true if find was used, but this is findOne.
This does indeed work with find. Spent two hours trying to find this information. Thank you.
OR console.log(user[0]._id);
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

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.