nodejs mongodb object id to string

node.jsMongodbMongoose

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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.

Solution 3 - node.js

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

Solution 4 - node.js

try this:

objectId.str;

see doc.

Solution 5 - node.js

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

Solution 6 - node.js

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

Solution 7 - node.js

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

Solution 8 - node.js

The result returned by find is an array.

Try this instead:

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

Solution 9 - node.js

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

Solution 10 - node.js

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.

Solution 11 - node.js

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

Solution 12 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwati SharmaView Question on Stackoverflow
Solution 1 - node.jsIonică BizăuView Answer on Stackoverflow
Solution 2 - node.jsAkerbeltZView Answer on Stackoverflow
Solution 3 - node.jsMauricio GiraldoView Answer on Stackoverflow
Solution 4 - node.jsanubiskongView Answer on Stackoverflow
Solution 5 - node.jsCédric NICOLASView Answer on Stackoverflow
Solution 6 - node.jsdavejoemView Answer on Stackoverflow
Solution 7 - node.jselrrrrrrrView Answer on Stackoverflow
Solution 8 - node.jsGiovanni DonelliView Answer on Stackoverflow
Solution 9 - node.jsDanielKhanView Answer on Stackoverflow
Solution 10 - node.jsBaDr AmerView Answer on Stackoverflow
Solution 11 - node.jsMasroor EjazView Answer on Stackoverflow
Solution 12 - node.jsisi.kacerView Answer on Stackoverflow