Convert ObjectID (Mongodb) to String in JavaScript

后端 未结 16 1253
青春惊慌失措
青春惊慌失措 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:28

    in the shell

    ObjectId("507f191e810c19729de860ea").str

    in js using the native driver for node

    objectId.toHexString()

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

    If someone use in Meteorjs, can try:

    In server: ObjectId(507f191e810c19729de860ea)._str.

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

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

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

    In Js do simply: _id.toString()

    For example:

    const myMongoDbObjId = ObjectID('someId');
    const strId = myMongoDbObjId.toString();
    console.log(typeof strId); // string
    
    0 讨论(0)
  • 2020-12-02 20:39

    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" }
      }}
    ])
    
    0 讨论(0)
  • 2020-12-02 20:43

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

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