将ObjectID(Mongodb)转换为JavaScript中的字符串

将ObjectID(Mongodb)转换为JavaScript中的字符串,javascript,mongodb,aggregation-framework,Javascript,Mongodb,Aggregation Framework,我想将ObjectID(Mongodb)转换为JavaScript中的字符串。 当我从MongoDB得到一个对象时。它就像一个对象有:timestamp,second,inc,machine。 我无法转换为字符串。下面是一个将中的ObjectId转换为字符串的工作示例 > a=db.dfgfdgdfg.findOne() { "_id" : ObjectId("518cbb1389da79d3a25453f9"), "d" : 1 } > a['_id'] ObjectId("518

我想将ObjectID(Mongodb)转换为JavaScript中的字符串。 当我从MongoDB得到一个对象时。它就像一个对象有:timestamp,second,inc,machine。
我无法转换为字符串。

下面是一个将中的
ObjectId
转换为字符串的工作示例

> 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
尝试了其他各种函数,如
toHexString()
,但没有成功。

尝试以下方法:

objectId.str

ObjectId()
具有以下属性和方法:

[……]

  • str
    -返回对象的十六进制字符串表示形式

实际上,您可以尝试以下方法:

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

ObjectId object+String将转换为String object。

假设OP希望使用Mongo 2.2或更高版本获取ObjectId的十六进制字符串值,则
valueOf()
方法将对象的表示形式返回为十六进制字符串。这也是通过
str
属性实现的

anubiskong帖子上的链接给出了所有细节,这里的危险是使用一种从较旧版本(例如,
变为字符串())的技术

ObjectId(“507f191e810c19729de860ea”).str

在js中


objectId.toHexString()

这样做,您就有了mongodb对象:
objectId(507f191e810c1972de860ea)
, 要获取
\u id
的字符串值,只需

ObjectId(507f191e810c19729de860ea).valueOf();
如果有人在Meteorjs中使用,可以尝试: 在服务器中:
ObjectId(507f191e810c19729de860ea)。\u str


在模板中:
{{collectionItem.\u id.\u str}}

只需使用这个:
\u id.$oid


然后得到ObjectId字符串。这是对象附带的。

使用这个简单的技巧,
您的对象。$id

我得到了一组mongo ID,下面是我所做的

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

...
使用toString:
var stringId=objectId.toString()

使用最新的节点MongoDB本机驱动程序(v3.0+):

您可以使用mongodb版本4.0中引入的聚合,将ObjectId转换为字符串

db.collection.aggregate([
  { "$project": {
    "_id": { "$toString": "$your_objectId_field" }
  }}
])

我觉得这很有趣,但对我来说很有效:

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

可以使用字符串格式


conststringid=`${objectId}`您可以使用
字符串

String(a['_id'])
如果您与MongoDB一起使用,它有一个内置的方法来获取ObjectID的字符串值。我成功地使用它执行了一个
if
语句,该语句使用
==
来比较字符串

从:

默认情况下,Mongoose为每个模式分配一个id虚拟getter,该getter将文档的_id字段强制转换为字符串,如果是ObjectID,则返回其hexString。如果不希望将id获取程序添加到模式中,可以通过在模式构建时传递此选项来禁用它


在Js中,只需执行以下操作:
\u id.toString()

例如:

const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
在Javascript中,String()使它变得简单

const id = String(ObjectID)

在聚合时使用$addFields

$addFields: {
      convertedZipCode: { $toString: "$zipcode" }
   }

“”+objectId
objectId.toString()
其中
objectId
是变量,我相信它会满足您的需要。从MongoDB加载的objectId是一个对象。如果您在Javascript中使用toString()函数,它将返回[Object,Object]。奇怪的是,这些函数本来应该实现的,我相信是fixedDunno将其标记为:的副本,但您大错特错了……我认为这不是个坏问题。!您的链接用于PHP。我需要JavaScript格式的。!。toHexString()为我工作,谢谢Sammaye!请改进您的回答字符串被包装在ObjectId中,因此为了获得包装值,您可以使用我刚才提供的答案@Ivan Barayevi不明白为什么,当我执行console.log时,这对我不起作用,我将ObjectId视为控制台上的一个对象这对我也不起作用。但是,
objectId.toString()
确实做到了。回答不错,它指出了使用本机驱动程序的区别。您可以在中看到这一点。您好,Hogan jerry,欢迎来到StackOverflow!请仅对代码部分使用代码格式,这样会更容易阅读:)祝您愉快!谢谢太激动了,需要一些explanation@sidgate,添加了一个示例ThankeThanked@Mar这只是让我免于序列化错误。