Convert ObjectID (Mongodb) to String in JavaScript

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.

Answers:

Answer

Try this:

objectId.str;

See the doc.

Answer

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.

Answer

in the shell

ObjectId("507f191e810c19729de860ea").str

in js using the native driver for node

objectId.toHexString()

Answer

Acturally, you can try this:

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

ObjectId object + String will convert to String object.

Answer

If someone use in Meteorjs, can try:

In server: ObjectId(507f191e810c19729de860ea)._str.

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

Answer

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

Answer

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

Answer

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/

Answer

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" }
  }}
])
Answer

Just use this : _id.$oid

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

Answer

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

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

...
Answer

You can use string formatting.

const stringId = `${objectId}`;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.