79

我想在 JavaScript 中将 ObjectID (Mongodb) 转换为 String。当我得到一个对象形式的 MongoDB 时。它就像一个对象有:时间戳,秒,公司,机器。我无法转换为字符串。

4

21 回答 21

117

尝试这个:

objectId.str

请参阅文档

ObjectId()具有以下属性和方法:

[...]

  • str- 返回对象的十六进制字符串表示。
于 2013-11-04T14:36:22.093 回答
26

这是将ObjectIdin 转换为字符串的工作示例

> a=db.dfgfdgdfg.findOne()
{ "_id" : ObjectId("518cbb1389da79d3a25453f9"), "d" : 1 }
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'].toString // This line shows you what the prototype does
function () {
    return "ObjectId(" + tojson(this.str) + ")";
}
> a['_id'].str // Access the property directly
518cbb1389da79d3a25453f9
> a['_id'].toString()
ObjectId("518cbb1389da79d3a25453f9") // Shows the object syntax in string form
> ""+a['_id'] 
518cbb1389da79d3a25453f9 // Gives the hex string

是否尝试了其他各种功能toHexString(),例如没有成功。

于 2013-05-10T09:22:41.577 回答
22

壳里

ObjectId("507f191e810c19729de860ea").str

在 js中使用节点的本机驱动程序

objectId.toHexString()

于 2016-06-22T16:12:38.133 回答
11

您可以使用mongodb 4.0$toString版中引入的聚合,它将 ObjectId 转换为字符串

db.collection.aggregate([
  { "$project": {
    "_id": { "$toString": "$your_objectId_field" }
  }}
])
于 2018-07-08T10:51:30.200 回答
9

使用 toString: var stringId = objectId.toString()

适用于最新的 Node MongoDB Native 驱动程序 (v3.0+):

http://mongodb.github.io/node-mongodb-native/3.0/

于 2018-06-26T20:10:24.113 回答
8

其实你可以试试这个:

> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'] + ''
"518cbb1389da79d3a25453f9"

ObjectId 对象 + String 将转换为 String 对象。

于 2013-12-06T01:37:39.230 回答
8

如果有人在 Meteorjs 中使用,可以尝试:

在服务器中:ObjectId(507f191e810c19729de860ea)._str

在模板中:{{ collectionItem._id._str }}.

于 2016-12-09T23:16:48.690 回答
6

假设 OP 想要获取 ObjectId 的十六进制字符串值,使用 Mongo 2.2 或更高版本,该valueOf()方法将对象的表示形式返回为十六进制字符串。这也是通过str属性实现的。

anubiskong 帖子上的链接提供了所有详细信息,这里的危险是使用从旧版本改变的技术,例如toString().

于 2015-04-14T02:48:42.280 回答
3

在 Js 中做的很简单:_id.toString()

例如:

const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
于 2020-11-04T13:16:32.830 回答
3

这行得通,你有 mongodb object: ObjectId(507f191e810c19729de860ea),要获取 的字符串值_id,你只需说

ObjectId(507f191e810c19729de860ea).valueOf();
于 2016-08-08T19:48:31.960 回答
3

在 Javascript 中,String() 让它变得简单

const id = String(ObjectID)
于 2020-12-23T03:57:19.380 回答
0

toString()方法为您提供十六进制字符串,它是一种 ascii 代码,但在基数 16 数字系统中。

将 id 转换为 24 个字符的十六进制字符串以进行打印

例如在这个系统中:

"a" -> 61
"b" -> 62
"c" -> 63

因此,如果您通过"abc..."获取objectId,您将获得“616263 ...”。

因此,如果您想从中获取可读的字符串(char 字符串),objectId则必须将其转换(hexCode 为 char)。

为此,我编写了一个实用函数hexStringToCharString()

function hexStringToCharString(hexString) {
  const hexCodeArray = [];

  for (let i = 0; i < hexString.length - 1; i += 2) {
    hexCodeArray.push(hexString.slice(i, i + 2));
  }

  const decimalCodeArray = hexCodeArray.map((hex) => parseInt(hex, 16));

  return String.fromCharCode(...decimalCodeArray);
}

并且有函数的用法

import { ObjectId } from "mongodb";

const myId = "user-0000001"; // must contains 12 character for "mongodb": 4.3.0
const myObjectId = new ObjectId(myId); // create ObjectId from string

console.log(myObjectId.toString()); // hex string >> 757365722d30303030303031
console.log(myObjectId.toHexString()); // hex string >> 757365722d30303030303031

const convertedFromToHexString = hexStringToCharString(
  myObjectId.toHexString(),
);

const convertedFromToString = hexStringToCharString(myObjectId.toString());

console.log(`convertedFromToHexString:`, convertedFromToHexString);
//convertedFromToHexString: user-0000001
console.log(`convertedFromToString:`, convertedFromToString);
//convertedFromToHexString: user-0000001

还有hexStringToCharString() 函数的TypeScript版本

function hexStringToCharString(hexString: string): string {
  const hexCodeArray: string[] = [];

  for (let i = 0; i < hexString.length - 1; i += 2) {
    hexCodeArray.push(hexString.slice(i, i + 2));
  }

  const decimalCodeArray: number[] = hexCodeArray.map((hex) =>
    parseInt(hex, 16),
  );

  return String.fromCharCode(...decimalCodeArray);
}
于 2022-01-18T08:40:41.170 回答
0

在聚合上使用 $addFields

$addFields: {
      convertedZipCode: { $toString: "$zipcode" }
   }
于 2021-05-08T17:39:14.177 回答
0

您可以使用字符串格式。

const stringId = `${objectId}`;

于 2020-07-03T13:19:00.217 回答
0

你可以使用String

String(a['_id'])
于 2020-09-22T23:35:17.203 回答
0

发现这真的很有趣,但它对我有用:

    db.my_collection.find({}).forEach((elm)=>{

    let value = new String(elm.USERid);//gets the string version of the ObjectId which in turn changes the datatype to a string.

    let result = value.split("(")[1].split(")")[0].replace(/^"(.*)"$/, '$1');//this removes the objectid completely and the quote 
    delete elm["USERid"]
    elm.USERid = result
    db.my_collection.save(elm)
    })
于 2019-05-14T22:32:38.060 回答
0

在 Mongoose 中,您可以使用 ObjectId 上的 toString() 方法来获取 24 个字符的十六进制字符串。

猫鼬文档

于 2021-11-27T11:15:21.213 回答
0

v4 文档(现在是最新版本)MongoDB NodeJS 驱动程序说: ObjectId 的方法 toHexString() 将 ObjectId id 作为 24 个字符的十六进制字符串表示形式返回。

于 2021-10-26T01:16:18.220 回答
0

只需使用这个:_id.$oid

你得到 ObjectId 字符串。这是随对象而来的。

于 2016-12-21T11:30:20.830 回答
-1

如果您将Mongoose与 MongoDB 一起使用,它有一个用于获取 ObjectID 的字符串值的内置方法。我成功地用它来做一个用来比较字符串的if语句。===

文档中:

Mongoose 默认为每个模式分配一个 id 虚拟 getter,它将文档的 _id 字段转换为字符串,或者在 ObjectIds 的情况下,返回其 hexString。如果您不希望将 id getter 添加到您的架构中,您可以通过在架构构建时传递此选项来禁用它。

于 2020-10-20T11:50:14.000 回答
-1

使用这个简单的技巧,your-object.$id

我得到了一系列 mongo Id,这就是我所做的。

jQuery:

...
success: function (res) {
   console.log('without json res',res);
    //without json res {"success":true,"message":" Record updated.","content":[{"$id":"58f47254b06b24004338ffba"},{"$id":"58f47254b06b24004338ffbb"}],"dbResponse":"ok"}

var obj = $.parseJSON(res);

if(obj.content !==null){
    $.each(obj.content, function(i,v){
        console.log('Id==>', v.$id);
    });
}

...
于 2017-04-25T08:13:30.590 回答