在JavaScript中将ObjectID(Mongodb)转换为字符串

93
我想在JavaScript中将ObjectID(Mongodb)转换为字符串。 当我从MongoDB中得到一个对象时,它看起来像是一个具有时间戳、秒数、增量和机器的对象。 我无法将其转换为字符串。

2
""+objectId 或者 objectId.toString(),其中 objectId 是我认为能满足你需求的变量。 - Sammaye
1
从MongoDB加载的ObjectID是一个对象。如果在Javascript中使用toString()函数,它将返回[Object,Object]。 - vhlen
奇怪,这些函数应该已经被实现了,我确定已经修复了。 - Sammaye
不知道是谁把这个标记为重复的:https://dev59.com/kF3Ua4cB1Zd3GeqP9yv3,但你是严重错误的... - Sammaye
幸运的是,下面的内容是JavaScript :) - Sammaye
显示剩余3条评论
22个回答

3

在JavaScript中,只需这样写:_id.toString()

例如:

const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string

2
需要一些解释。 - sidgate
@sidgate,添加了一个示例。 - Mar
1
谢谢@Mar,这刚刚救了我免受序列化错误的困扰。 - cdaiga

1

toString()方法会给出一个十六进制字符串,这种字符串类似于ASCII码,但是使用的是十六进制数系统。

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

例如,在此系统中:

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

如果您将"abc..."传递给objectId,则会得到"616263..."。

因此,如果您想从objectId获取可读字符串(char字符串),则必须将其转换为十六进制代码(hexCode to 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

还有一个TypeScript版本的hexStringToCharString()函数。

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

1
你可以使用字符串格式化。

const stringId = `${objectId}`;


0

在聚合操作中使用 $addFields

$addFields: {
      convertedZipCode: { $toString: "$zipcode" }
   }

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

你好Hogan Jerry,欢迎来到StackOverflow!请只在代码部分使用代码格式,这样阅读会更容易 :) 祝您有愉快的一天! - Y-B Cause
1
谢谢...我太兴奋了。 - Hogan jerry

0

只需使用这个:_id.$oid

你就可以得到ObjectId字符串。它随对象一起返回。


你可以在Strict MongoDB Extended JSON中看到。 - Sergio

0

目前最新版本的 MongoDB NodeJS 驱动程序 v4 的文档中提到:ObjectId 的 toHexString() 方法将返回一个由 24 个字符组成的十六进制字符串,表示 ObjectId 的 id。


0
在Mongoose中,您可以使用toString()方法对ObjectId进行操作,以获取一个24个字符的十六进制字符串。 Mongoose文档

0

以下三种方法可用于获取id的字符串版本。
(这里newUser是一个包含要存储在mongodb文档中的数据的对象)

newUser.save((err, result) => {
  if (err) console.log(err)
  else {
     console.log(result._id.toString()) //Output - 23f89k46546546453bf91
     console.log(String(result._id))    //Output - 23f89k46546546453bf91
     console.log(result._id+"")         //Output - 23f89k46546546453bf91
  }
});

-1
你可以使用 String
String(a['_id'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接