[英]NodeJS, using MongoDB Native driver, how do I convert ObjectID to string
I am using MongoDB native driver for NodeJS, and am having trouble converting ObjectID
to a string
. 我正在为NodeJS使用MongoDB本机驱动程序,并且无法将
ObjectID
转换为string
。
My code looks like: 我的代码看起来像:
db.collection('user', function(err, collection) {
collection.insert(data, {safe:true}, function(err, result) {
var myid = result._id.toString();
console.log(myid);
)};
});
I have tried various suggestions on StackOverflow like: 我在StackOverflow上尝试了各种建议,如:
myid = result._id.toString();
myid = result._id.toHexString();
but none of them seemed to work. 但他们似乎都没有工作。
I am trying to convert the ObjectID
to base64
encoding. 我试图将
ObjectID
转换为base64
编码。
Not sure if I am running into supported functionality under the Mongo native driver. 不确定我是否遇到了Mongo本机驱动程序下的受支持功能。
This work for me: 这项工作对我来说:
var ObjectID = require('mongodb').ObjectID;
var idString = '4e4e1638c85e808431000003';
var idObj = new ObjectID(idString);
console.log(idObj);
console.log(idObj.toString());
console.log(idObj.toHexString());
Output: 输出:
4e4e1638c85e808431000003
4e4e1638c85e808431000003
4e4e1638c85e808431000003
insert
returns an array of results (as you can also send an array of objects to be inserted), so your code is trying to get the _id
from the array instance rather than the first result: insert
返回一个结果数组(因为你也可以发送一个要插入的对象数组),所以你的代码试图从数组实例而不是第一个结果中获取_id
:
MongoClient.connect("mongodb://localhost:27017/testdb", function(err, db) {
db.collection("user").insert({name:'wiredprairie'}, function(err, result) {
if (result && result.length > 0) {
var myid = result[0]._id.toString();
console.log(myid);
}
});
});
Also, you won't need to base64 encode the result of calling toString
on an ObjectId
as it's returned as a hex number already. 此外,您不需要对
ObjectId
上调用toString
的结果进行base64编码,因为它已经作为十六进制数返回。 You could also call: result[0]._id.toHexString()
to get the Hex value directly ( toString
just wraps toHexString
). 您还可以调用:
result[0]._id.toHexString()
直接获取Hex值( toString
只包含toHexString
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.