乐闻世界logo
搜索文章和话题

How to convert objectid to string in mongoose?

5 个月前提问
3 个月前修改
浏览次数112

6个答案

1
2
3
4
5
6

在Mongoose中,每个模型的文档都有一个_id属性,这个属性默认是一个ObjectId类型。ObjectId是MongoDB中的一种数据类型,通常用于唯一标识文档。

如果你需要将ObjectId转换为字符串,有几种方法可以做到:

  1. 使用toString()方法: 每个ObjectId对象都有一个toString()方法,可以调用它来将ObjectId转换为24位的十六进制字符串。

    javascript
    const idAsString = myDocument._id.toString();
  2. 使用String构造函数: 你也可以直接用String构造函数将ObjectId转换为字符串。

    javascript
    const idAsString = String(myDocument._id);
  3. 使用 ES6 模板字符串: ES6 引入了模板字符串,你可以简单地将ObjectId嵌入到模板字符串中,它将自动调用ObjectIdtoString()方法。

    javascript
    const idAsString = `${myDocument._id}`;
  4. 在查询时直接转换: 如果你在查询时就想获取字符串形式的_id,可以使用Mongoose的虚拟属性功能,将_id字段设置为虚拟的字符串类型字段。

    javascript
    schema.virtual('id').get(function(){ return this._id.toHexString(); }); // 然后可以这样获取字符串形式的_id const idAsString = myDocument.id;

以上方法可以根据需要在不同场合下使用。例如,如果你正在编写一个API并且需要在JSON响应中返回_id,由于ObjectId不是一个标准的JSON数据类型,你可能需要将其转换为字符串。如果你在Mongoose中使用虚拟属性,你还可以让Mongoose在将文档转换为JSON时自动执行这种转换。

2024年6月29日 12:07 回复

Try this:

shell
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:

shell
console.log(user._id.toString());
2024年6月29日 12:07 回复

Take the underscore out and try again:

shell
console.log(user.id)

Also, the value returned from id is already a string, as you can see here.

2024年6月29日 12:07 回复

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

shell
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. } })
2024年6月29日 12:07 回复

try this:

shell
objectId.str;

see doc.

2024年6月29日 12:07 回复

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

shell
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

2024年6月29日 12:07 回复

你的答案