繁体   English   中英

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

[英]Convert ObjectID (Mongodb) to String in JavaScript

我想将 ObjectID (Mongodb) 转换为 JavaScript 中的字符串。 当我从 MongoDB 收到 Object 时。 它就像 object 一样具有:时间戳,秒,公司,机器。 我无法转换为字符串。

尝试这个:

objectId.str

请参阅文档

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

[...]

  • str - 返回 object 的十六进制字符串表示形式。

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

> 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()没有成功。

shell

ObjectId("507f191e810c19729de860ea").str

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

objectId.toHexString()

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

db.collection.aggregate([
  { "$project": {
    "_id": { "$toString": "$your_objectId_field" }
  }}
])

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

与最新的 Node MongoDB 原生驱动程序 (v3.0+) 一起使用:

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

其实你可以试试这个:

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

ObjectId object + 字符串将转换为字符串 object。

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

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

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

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

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

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

const id = String(ObjectID)

这个工作,你有 mongodb object: ObjectId(507f191e810c19729de860ea) ,得到_id的字符串值,你只是说

ObjectId(507f191e810c19729de860ea).valueOf();

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

例如:

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

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

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

例如在这个系统中:

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

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

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

为此,我编写了一个实用程序 function 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);
}

并且使用了 function

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() function 的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);
}

只需使用这个: _id.$oid

你得到 ObjectId 字符串。 这与 object 一起提供。

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

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

您可以使用字符串格式。

 const stringId = `${objectId}`;

在聚合上使用 $addFields

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

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

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

Mongoose 文档

以下三种方法可用于获取 id 的字符串版本。
(这里的 newUser 是一个 object 包含要存储在 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
  }
});

使用这个简单的技巧, 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);
    });
}

...

你可以使用String

String(a['_id'])

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

文档中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM