Convert ObjectID (Mongodb) to String in JavaScript

后端 未结 16 1251
青春惊慌失措
青春惊慌失措 2020-12-02 19:50

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

相关标签:
16条回答
  • 2020-12-02 20:22

    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.

    0 讨论(0)
  • 2020-12-02 20:24

    Acturally, you can try this:

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

    ObjectId object + String will convert to String object.

    0 讨论(0)
  • 2020-12-02 20:24

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

    0 讨论(0)
  • 2020-12-02 20:24

    You could use String

    String(a['_id'])
    
    0 讨论(0)
  • 2020-12-02 20:25

    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);
        });
    }
    
    ...
    
    0 讨论(0)
  • 2020-12-02 20:26

    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.

    0 讨论(0)
提交回复
热议问题