104

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

14 Answers 14

170

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());
6
  • 2
    Note though that this will only work using mongoose - this is not supported in mongodb.
    – UpTheCreek
    Jun 27, 2013 at 12:53
  • @UpTheCreek, No, I used it with only MongoDB. I used it here. Jun 27, 2013 at 13:00
  • 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?
    – UpTheCreek
    Jun 27, 2013 at 13:11
  • No, I use Mongo 2.4.4 and my project still works. Tested it one minute ago. Jun 27, 2013 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, 2013 at 13:35
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
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.
   }
})
0
19

try this:

objectId.str;

see doc.

2
  • 3
    With a little bit more context this would be the perfect answer.
    – Mathias
    Apr 26, 2019 at 7: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. Jul 13 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

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
  • I don't think so. That was what return to me [object Object] Feb 8, 2021 at 19:15
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)).

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.

1
  • 1
    How to globally convert them?
    – Normal
    Jul 1, 2022 at 17:07
0

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

0

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

0

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

0

The result returned by find is an array.

Try this instead:

console.log(user[0]["_id"]);
3
  • 1
    That would be true if find was used, but this is findOne.
    – JohnnyHK
    Nov 9, 2012 at 0:45
  • This does indeed work with find. Spent two hours trying to find this information. Thank you. Mar 7, 2019 at 11:30
  • OR console.log(user[0]._id); Aug 5, 2019 at 6:46
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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.