我想在 JavaScript 中将 ObjectID (Mongodb) 转换为字符串。 当我从 MongoDB 获取对象时。它就像一个对象有:时间戳、秒、公司、机器。 我无法转换为字符串。
试试这个:
// mongo shell
objectId.str
// mongo client, JS, Node.js
objectId.toString()
请参阅文档。
有以下属性和方法:ObjectId()
- 返回对象的十六进制字符串表示形式。str
.toString()
添加自@J.C.的评论
这是将
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()
,但没有成功。
使用 toString:
var stringId = objectId.toString()
与最新的 Node MongoDB Native 驱动程序 (v3.0+) 配合使用:
其实,你可以试试这个:
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'] + ''
"518cbb1389da79d3a25453f9"
ObjectId 对象 + String 将转换为 String 对象。
在服务器中:
ObjectId(507f191e810c19729de860ea)._str
。
在模板中:
{{ collectionItem._id._str }}
。
假设OP想要获取ObjectId的十六进制字符串值,使用Mongo 2.2或更高版本,
valueOf()
方法将对象的表示形式返回为十六进制字符串。这也可以通过 str
属性来实现。
anubiskong 帖子上的链接提供了所有详细信息,这里的危险是使用从旧版本更改的技术,例如
toString()
。
在 Javascript 中,String() 让一切变得简单
const id = String(ObjectID)
这有效,你有 mongodb 对象:
ObjectId(507f191e810c19729de860ea)
,
要获取 _id
的字符串值,只需输入
ObjectId(507f191e810c19729de860ea).valueOf();
在Js中简单地做:
_id.toString()
例如:
const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
您可以使用字符串格式。
const stringId = `${objectId}`;
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);
}
就用这个:
_id.$oid
您将获得 ObjectId 字符串。这是随物品一起来的。
发现这真的很有趣,但它对我有用:
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)
})
聚合时使用 $addFields
$addFields: {
convertedZipCode: { $toString: "$zipcode" }
}
v4 的文档(现在是最新版本)MongoDB NodeJS 驱动程序说:ObjectId 的 toHexString() 方法以 24 个字符的十六进制字符串表示形式返回 ObjectId id。
在 Mongoose 中,您可以对 ObjectId 使用 toString() 方法来获取 24 个字符的十六进制字符串。
以下三种方法可用于获取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
}
});
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
使用这个简单的技巧,
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'])