Convert ObjectID (Mongodb) to String in JavaScript
Asked Answered
T

23

94

I want to convert ObjectID (Mongodb) to String in JavaScript. When I get a Object form MongoDB. it like as a object has: timestamp, second, inc, machine. I can't convert to string.

Transect answered 10/5, 2013 at 8:58 Comment(8)
""+objectId or objectId.toString() whereby objectId is the variable I believe will do what your looking for.Postrider
ObjectID loaded from MongoDB is a Object. if you use toString() function in Javascript, It will return [Object, Object].Transect
Odd, those functions were supposed to be implemented, I am sure that was fixedPostrider
Dunno who marked this a duplicate of: https://mcmap.net/q/225280/-mongodb-objectid-to-string but you are seriously wrong...Postrider
I think it's not bad question.! Your link is used for PHP. I need it in JavaScript.!Transect
Indeed fortunately the stuff below is javascript :)Postrider
@Transect what worked for you? i am also getting [Object, Object]Beanie
I think there is some confusion in the answers as to whether you are talking about the mongodb console, or the javascript driver for node (both are JS, but are not identical in usage unfortunately)Sunk
P
132

Try this:

// mongo shell
objectId.str

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

See the doc.

ObjectId() has the following attribute and methods:

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

.toString() added from comment of @J.C.

Pedicab answered 4/11, 2013 at 14:36 Comment(4)
i dont understand why, this isnt working for me when i do a console.log, i see the objectId as an object on the consoleBeanie
This didn't work for me either. However, objectId.toString() did.Birdsall
objectId.str is for mongo shell, objectId.toString() is for mongo clientPeel
What is the solution for monk? Neither .str or .toString() are working I am just getting an object, where the display is the exact string I am after but doesn't match equality checks against another stringReplace
P
30

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.

Postrider answered 10/5, 2013 at 9:22 Comment(2)
.toHexString() worked for me thanks Sammaye! mongodb.github.io/node-mongodb-native/api-bson-generated/…Zoosporangium
As of 2022 there's no .str - the only viable way to convert an ObjectId to String is through .toString()Octastyle
J
29

in the shell

ObjectId("507f191e810c19729de860ea").str

in js using the native driver for node

objectId.toHexString()

Joellyn answered 22/6, 2016 at 16:12 Comment(2)
Nice answer, which points out the difference using native driver.Frisse
This is the case if you're using a client like NoSQLBooster. Thanks.Shirring
D
16

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" }
  }}
])
Damon answered 8/7, 2018 at 10:51 Comment(0)
F
10

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/

Furr answered 26/6, 2018 at 20:10 Comment(0)
R
9

Acturally, you can try this:

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

ObjectId object + String will convert to String object.

Redevelop answered 6/12, 2013 at 1:37 Comment(0)
W
8

If someone use in Meteorjs, can try:

In server: ObjectId(507f191e810c19729de860ea)._str.

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

Wriggler answered 9/12, 2016 at 23:16 Comment(0)
K
6

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().

Keble answered 14/4, 2015 at 2:48 Comment(0)
S
6

In Javascript, String() make it easy

const id = String(ObjectID)
Shill answered 23/12, 2020 at 3:57 Comment(0)
Z
5

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

ObjectId(507f191e810c19729de860ea).valueOf();
Zeculon answered 8/8, 2016 at 19:48 Comment(2)
Please improve your answerNicholenicholl
the string is wrapped inside ObjectId, so to get the wrapped value you use the answer i just provided @ Ivan BarayevZeculon
C
3

In Js do simply: _id.toString()

For example:

const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
Concern answered 4/11, 2020 at 13:16 Comment(3)
needs some explanationBurette
@sidgate, added an exampleConcern
Thanks @Concern this just save me from a serialization bug.Wideopen
T
1

You can use string formatting.

const stringId = `${objectId}`;
Tungsten answered 3/7, 2020 at 13:19 Comment(0)
A
1

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);
}
Arabelle answered 18/1, 2022 at 8:40 Comment(0)
T
0

Just use this : _id.$oid

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

Terrell answered 21/12, 2016 at 11:30 Comment(1)
You can see that at Strict MongoDB Extended JSON.Terrell
S
0

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)
    })
Saddleback answered 14/5, 2019 at 22:32 Comment(2)
Hello Hogan jerry, and welcome to StackOverflow! Please use code formatting only for the code parts, it will be easier to read :) Have a good day!Roesch
Thanks... was too excitedSaddleback
U
0

On aggregation use $addFields

$addFields: {
      convertedZipCode: { $toString: "$zipcode" }
   }
Unitarian answered 8/5, 2021 at 17:39 Comment(0)
T
0

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.

Tearing answered 26/10, 2021 at 1:16 Comment(0)
C
0

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

Mongoose documentation

Chiron answered 27/11, 2021 at 11:15 Comment(0)
C
0

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
  }
});
Crossly answered 2/7, 2022 at 1:43 Comment(0)
I
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
Integrity answered 12/4 at 12:9 Comment(0)
C
-1

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

...
Cecillececily answered 25/4, 2017 at 8:13 Comment(0)
G
-1

You could use String

String(a['_id'])
Gayton answered 22/9, 2020 at 23:35 Comment(0)
M
-2

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.

Mentalism answered 20/10, 2020 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.