问题描述
我正在使用node.js开发restAPI,我正在尝试查询mongo集合。我可以使用字符串查询(例如companyname),但我需要能够查询文档中的_id元素。
I'm developing a restAPI using node.js and i'm trying to query a mongo collection. I can query using strings (for example "companyname") but I need to be able to query the "_id" element in the document.
在mongo中,_id目前存储如下(作为GUID):
In mongo the _id is currently stored like this (as a GUID):
{
"_id" : new BinData(3, "MH+t3q6PD0SxVR5z7/pzfw=="),
"companyname" : "TestCompany",
"databasename" : "TestDataBase",
}
这是我目前的GET方法:
This is what my current GET method looks like:
exports.getBusinessCardData = function(req, res) {
var id = req.params.id;
//"id" = MH+t3q6PD0SxVR5z7/pzfw==
tradeShowAdminDB.collection('clients', function(err, collection) {
collection.findOne({'_id': id}, function(err, item) {
res.send(item);
});
});
};
进入方法的id是Base64字符串格式(MH + t3q6PD0SxVR5z7 / pzfw == )并使用该查询返回任何内容(我假设它不是正确的类型/格式)。我的问题是如何将id转换为正确的格式,以便我可以使用_id查询mongo?
The "id" coming into the method is Base64 string format ("MH+t3q6PD0SxVR5z7/pzfw==") and using that the query returns nothing (i'm assuming as it's not the correct type/format). My question is how do I get that "id" into the correct format so that I can query mongo using the _id?
我一直在寻找年龄而且可以'似乎找到了解决方案,文档似乎非常模糊,不是24字符十六进制ObjectId。任何帮助将非常感谢!
其他信息:
I've been looking for ages and can't seem to find a solution and the documentation seems very vague on anything that isn't a 24 character hex ObjectId. Any help would be very much appreciated!
Additional information:
我正在使用节点v0.10.33并表达v4。 x
I'm using node v0.10.33 and express v4.x
我使用的mongo驱动程序只是节点的基本javascript mongo驱动程序。
(在此处找到:)
The mongo driver I am using is just the base javascript mongo driver for node.
(found here: http://docs.mongodb.org/ecosystem/drivers/node-js/)
推荐答案
好的我找到了获得解决方案的解决方案将base64字符串转换为节点内的GUID格式,要转换它需要完成:
Ok i've found the solution to get the base64 string into a GUID format within node, to convert it this needs to be done:
var mongo.require('mongodb');
var GUID = new mongo.Binary(new Buffer(<base65String>, 'base64'), 3);
现在我可以像这样查询数据库:
and now i can query the database like this:
collection.findOne({'_id' : GUID}, function(err, item) {
res.send(item);
});
这篇关于Mongo和Node.js:使用UUID(GUID)通过_id查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!