nodejs mongodb object id to string

2019-01-22 06:26发布

问题:

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?

回答1:

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


回答2:

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.

I'm using it this way and it works.

Cheers



回答3:

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

I hope this help.



回答4:

try this: objectId.str;

see doc.



回答5:

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



回答6:

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



回答7:

When using mongoose .

A representation of the _id is usually in the form (recieved 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") })


回答8:

I faced the same problem and .toString() worked for me. I'm using mongojs driver. Here was my question

Mongodb find is not working with the Objectid



回答9:

The result returned by find is an array.

Try this instead:

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



回答10:

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