我想将ObjectID (Mongodb)转换为JavaScript中的字符串。当我得到一个对象从MongoDB。它就像一个对象有:时间戳,秒数,机器。我不能转换成字符串
试试这个:
// mongo shell
objectId.str
// mongo client, JS, Node.js
objectId.toString()
见文档
ObjectId()
具有以下属性和方法:
str
-返回对象的十六进制字符串表示。
.toString()
添加自@ j.c.的评论
ObjectId("507f191e810c19729de860ea").str
在js中使用本地驱动程序为node
objectId.toHexString()
下面是将 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 driver (v3.0+):
http://mongodb.github.io/node-mongodb-native/3.0/实际上,您可以这样尝试:
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'] + ''
"518cbb1389da79d3a25453f9"
objecd对象+ String将转换为String对象
如果有人在Meteorjs中使用,可以尝试:
在服务器: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码,但在十六进制中。
将id转换为24个字符的十六进制字符串,用于打印
例如:
"a" -> 61
"b" -> 62
"c" -> 63
如果你通过"abc..."
得到objectId
,你会得到"616263…"
因此,如果你想从objectId
获得可读的字符串(char字符串),你必须转换它(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
还有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驱动程序说:objecd的toHexString()方法返回objecd id作为24个字符的十六进制字符串表示。
在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
}
});
使用这个简单的技巧,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
语句,使用===
来比较字符串。
来自文档:
Mongoose在默认情况下为每个模式分配一个id虚拟getter,它返回文档的_id字段转换为字符串,或者在ObjectIds的情况下,它的hexString。如果你不想在你的模式中添加id getter,你可以通过在模式构建时传递这个选项来禁用它。