在 JavaScript 中将 ObjectID (Mongodb)转换为 String

我想在 JavaScript 中将 ObjectID (Mongodb)转换为 String。 当我从 MongoDB 获得一个对象时,它就像一个对象一样有: 时间戳,秒,公司,机器。 我不能转换成字符串。

126865 次浏览

Here is a working example of converting the ObjectId in to a string

> 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

Did try various other functions like toHexString() with no success.

Try this:

objectId.str

See the doc.

ObjectId() has the following attribute and methods:

[...]

  • str - Returns the hexadecimal string representation of the object.

Acturally, you can try this:

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

ObjectId object + String will convert to String object.

Assuming the OP wants to get the hexadecimal string value of the ObjectId, using Mongo 2.2 or above, the valueOf() method returns the representation of the object as a hexadecimal string. This is also achieved with the str property.

The link on anubiskong's post gives all the details, the danger here is to use a technique which has changed from older versions e.g. toString().

in the shell

ObjectId("507f191e810c19729de860ea").str

in js using the native driver for node

objectId.toHexString()

this works, You have mongodb object: ObjectId(507f191e810c19729de860ea), to get string value of _id, you just say

ObjectId(507f191e810c19729de860ea).valueOf();

If someone use in Meteorjs, can try:

In server: ObjectId(507f191e810c19729de860ea)._str.

In template: \{\{ collectionItem._id._str }}.

Just use this : _id.$oid

And you get the ObjectId string. This come with the object.

Use this simple trick, your-object.$id

I am getting an array of mongo Ids, here is what I did.

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


...

Use toString: var stringId = objectId.toString()

Works with the latest Node MongoDB Native driver (v3.0+):

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

You can use $toString aggregation introduced in mongodb version 4.0 which converts the ObjectId to string

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

Found this really funny but it worked for me:

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

You can use string formatting.

const stringId = `${objectId}`;

You could use String

String(a['_id'])

If you're using Mongoose along with MongoDB, it has a built-in method for getting the string value of the ObjectID. I used it successfully to do an if statement that used === to compare strings.

From the documentation:

Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an id getter added to your schema, you may disable it by passing this option at schema construction time.

In Js do simply: _id.toString()

For example:

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

In Javascript, String() make it easy

const id = String(ObjectID)

On aggregation use $addFields

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

Documentation of v4 (right now it's latest version) MongoDB NodeJS Driver says: Method toHexString() of ObjectId returns the ObjectId id as a 24 character hex string representation.

In Mongoose, you can use toString() method on ObjectId to get a 24-character hexadecimal string.

Mongoose documentation

toString() method gives you hex String which is kind of ascii code but in base 16 number system.

Converts the id into a 24 character hex string for printing

For example in this system:

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

So if you pass "abc..." to get objectId you will get "616263...".

As a result if you want to get readable string(char string) from objectId you have to convert it(hexCode to char).

To do this I wrote an utility 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);
}

and there is usage of the 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

And there is also TypeScript version of hexStringToCharString() function

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

Below three methods can be used to get the string version of id.
(Here newUser is an object containing the data to be stored in the mongodb document)

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