nodejs mongodb 对象 id 到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13104690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:33:06  来源:igfitidea点击:

nodejs mongodb object id to string

node.jsmongodbmongoose

提问by Swati Sharma

IN nodejs, with mongodb, mongoosejs as orm

在 nodejs 中,以 mongodb、mongoosejs 作为 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?

为什么?以及如何将 _id 字符串化呢?

回答by Ionic? Biz?u

Try this:

尝试这个:

user._id.toString()

A MongoDB ObjectIdis 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 consoleusing console.log.

MongoDB中的ObjectId是一个12字节的UUID可以用作与长度为24个字符一个HEX字符串表示。您需要将其转换为字符串以console使用console.log.

So, you have to do this:

所以,你必须这样做:

console.log(user._id.toString());

回答by AkerbeltZ

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.

此外,从 id 返回的值已经是一个字符串,正如您在此处看到的。

I'm using it this way and it works.

我正在以这种方式使用它并且它有效。

Cheers

干杯

回答by Mauricio Giraldo

I'm using mongojs, and i have this example:

我正在使用 mongojs,我有这个例子:

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.

我希望这会有所帮助。

回答by anubiskong

try this: objectId.str;

试试这个:objectId.str;

see doc.

文档

回答by Cédric NICOLAS

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

如果您使用的是 Mongoose,那么确保将 id 作为十六进制字符串的唯一方法似乎是:

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

这是因为 object._id 仅在对象被填充时才存在,否则对象是 ObjectId

回答by Giovanni Donelli

The result returned by find is an array.

find 返回的结果是一个数组。

Try this instead:

试试这个:

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

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

回答by elrrrrrrr

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

在 mongoose 中,objectId 是一个对象(console.log(typeof it._id))。

回答by davejoem

When using mongoose .

使用猫鼬时。

A representation of the _id is usually in the form (recieved client side)

_id 的表示通常采用以下形式(收到的客户端)

{ _id: { _bsontype: 'ObjectID', id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },

{ _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)

正如你所看到的,那里有一个缓冲区。转换它的最简单方法就是做<obj>.toString()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") })

回答by Peter the Russian

There are two ways to do this:

有两种方法可以做到这一点:

  1. in stead of using user._iduse user.idand it will return a string for you
  2. If you really want to go the long way around you can use user._id.toString()
  1. 而不是使用user._iduse user.id,它将为您返回一个字符串
  2. 如果你真的想走很长的路,你可以使用 user._id.toString()

回答by Pritam Karmakar

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

我遇到了同样的问题, .toString() 对我来说有效。我正在使用mongojs 驱动程序。这是我的问题

Mongodb find is not working with the Objectid

Mongodb find 不适用于 Objectid