对象 id 到字符串

在 Nodejs,与 mongodb,mongosejs 作为形式

我要这么做

我有一个模型,用户

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

为什么? 那么如何得到字符串的 _ id 呢?

153010 次浏览

The result returned by find is an array.

Try this instead:

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

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.

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

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

try this:

objectId.str;

see doc.

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

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

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

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

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.

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

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