我想在 JavaScript 中将 ObjectID (Mongodb) 转换为 String。当我得到一个对象形式的 MongoDB 时。它就像一个对象有:时间戳,秒,公司,机器。我无法转换为字符串。
21 回答
这是将ObjectId
in 转换为字符串的工作示例
> 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()
,例如没有成功。
您可以使用mongodb 4.0$toString
版中引入的聚合,它将 ObjectId 转换为字符串
db.collection.aggregate([
{ "$project": {
"_id": { "$toString": "$your_objectId_field" }
}}
])
使用 toString:
var stringId = objectId.toString()
适用于最新的 Node MongoDB Native 驱动程序 (v3.0+):
其实你可以试试这个:
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'] + ''
"518cbb1389da79d3a25453f9"
ObjectId 对象 + String 将转换为 String 对象。
如果有人在 Meteorjs 中使用,可以尝试:
在服务器中:ObjectId(507f191e810c19729de860ea)._str
。
在模板中:{{ collectionItem._id._str }}
.
假设 OP 想要获取 ObjectId 的十六进制字符串值,使用 Mongo 2.2 或更高版本,该valueOf()
方法将对象的表示形式返回为十六进制字符串。这也是通过str
属性实现的。
anubiskong 帖子上的链接提供了所有详细信息,这里的危险是使用从旧版本改变的技术,例如toString()
.
在 Js 中做的很简单:_id.toString()
例如:
const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
这行得通,你有 mongodb object: ObjectId(507f191e810c19729de860ea)
,要获取 的字符串值_id
,你只需说
ObjectId(507f191e810c19729de860ea).valueOf();
在 Javascript 中,String() 让它变得简单
const id = String(ObjectID)
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);
}
在聚合上使用 $addFields
$addFields: {
convertedZipCode: { $toString: "$zipcode" }
}
您可以使用字符串格式。
const stringId = `${objectId}`;
你可以使用String
String(a['_id'])
发现这真的很有趣,但它对我有用:
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)
})
在 Mongoose 中,您可以使用 ObjectId 上的 toString() 方法来获取 24 个字符的十六进制字符串。
v4 文档(现在是最新版本)MongoDB NodeJS 驱动程序说: ObjectId 的方法 toHexString() 将 ObjectId id 作为 24 个字符的十六进制字符串表示形式返回。
只需使用这个:_id.$oid
你得到 ObjectId 字符串。这是随对象而来的。
使用这个简单的技巧,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);
});
}
...