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

问题描述 投票:0回答:23

我想在 JavaScript 中将 ObjectID (Mongodb) 转换为字符串。 当我从 MongoDB 获取对象时。它就像一个对象有:时间戳、秒、公司、机器。 我无法转换为字符串。

javascript mongodb aggregation-framework
23个回答
132
投票

试试这个:

// mongo shell
objectId.str

// mongo client, JS, Node.js
objectId.toString()

请参阅文档

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

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

.toString()
添加自@J.C.

的评论

30
投票

这是将

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


29
投票

壳里

ObjectId("507f191e810c19729de860ea").str

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

objectId.toHexString()


16
投票

您可以使用 mongodb 版本 4.0 中引入的

$toString 聚合,将 ObjectId 转换为字符串

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

10
投票

使用 toString:

var stringId = objectId.toString()

与最新的 Node MongoDB Native 驱动程序 (v3.0+) 配合使用:

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


9
投票

其实,你可以试试这个:

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

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


8
投票

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

在服务器中:

ObjectId(507f191e810c19729de860ea)._str

在模板中:

{{ collectionItem._id._str }}


6
投票

假设OP想要获取ObjectId的十六进制字符串值,使用Mongo 2.2或更高版本,

valueOf()
方法将对象的表示形式返回为十六进制字符串。这也可以通过
str
属性来实现。

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

toString()


6
投票

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

const id = String(ObjectID)

5
投票

这有效,你有 mongodb 对象:

ObjectId(507f191e810c19729de860ea)
, 要获取
_id
的字符串值,只需输入

ObjectId(507f191e810c19729de860ea).valueOf();

3
投票

在Js中简单地做:

_id.toString()

例如:

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

1
投票

您可以使用字符串格式。

const stringId = `${objectId}`;


1
投票

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

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

以本系统为例:

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

因此,如果您通过

"abc..."
获得
objectId
,您将得到“616263...”。

因此,如果您想从

objectId
获取可读字符串(字符字符串),您必须将其转换(十六进制代码到字符)。

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

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

0
投票

就用这个:

_id.$oid

您将获得 ObjectId 字符串。这是随物品一起来的。


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

0
投票

聚合时使用 $addFields

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

0
投票

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


0
投票

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

猫鼬文档


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

0
投票
user: {
  _id: ObjectId('234578fbf161fefa4b4efc')
  userId: ObjectId('234578fbf161fefa4b4efc')
}
console.log(user._id)            // new ObjectId('234578fbf161fefa4b4efc')
console.log(user.id)             // 234578fbf161fefa4b4efc

console.log(user.userId)         // new ObjectId('234578fbf161fefa4b4efc')
console.log(String(user.userId)) // 234578fbf161fefa4b4efc

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

...

-1
投票

你可以使用

String

String(a['_id'])

-2
投票

如果您将 Mongoose 与 MongoDB 一起使用,它有一个内置方法用于获取 ObjectID 的字符串值。我成功地使用它来执行一个使用

if
来比较字符串的
===
语句。

来自文档

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

© www.soinside.com 2019 - 2024. All rights reserved.