Convert ObjectID (Mongodb) to String in JavaScript

2019-01-13 17:22发布

问题:

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.

回答1:

Try this:

objectId.str;

See the doc.



回答2:

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.



回答3:

in the shell

ObjectId("507f191e810c19729de860ea").str

in js using the native driver for node

objectId.toHexString()



回答4:

Acturally, you can try this:

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

ObjectId object + String will convert to String object.



回答5:

If someone use in Meteorjs, can try:

In server: ObjectId(507f191e810c19729de860ea)._str.

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



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



回答7:

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



回答8:

Just use this : _id.$oid

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



回答9:

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/



回答10:

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


回答11:

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

...