[英]Mongo and Node.js: Finding a document by _id using a UUID (GUID)
I'm developing a restAPI using node.js and i'm trying to query a mongo collection. 我正在使用node.js开发restAPI,并且尝试查询mongo集合。 I can query using strings (for example "companyname") but I need to be able to query the "_id" element in the document. 我可以使用字符串查询(例如“ companyname”),但我需要能够查询文档中的“ _id”元素。
In mongo the _id is currently stored like this (as a GUID): 在mongo中,_id当前以这种方式存储(作为GUID):
{
"_id" : new BinData(3, "MH+t3q6PD0SxVR5z7/pzfw=="),
"companyname" : "TestCompany",
"databasename" : "TestDataBase",
}
This is what my current GET method looks like: 这是我当前的GET方法的样子:
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);
});
});
};
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). 该方法中使用的“ id”是Base64字符串格式(“ MH + t3q6PD0SxVR5z7 / pzfw ==”),并使用该查询不返回任何内容(我假设这不是正确的类型/格式)。 My question is how do I get that "id" into the correct format so that I can query mongo using the _id? 我的问题是如何将“ id”转换为正确的格式,以便可以使用_id查询mongo?
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. 我一直在寻找年龄,似乎无法找到解决方案,并且该文档对于不是24个字符的十六进制ObjectId的文档似乎非常含糊。 Any help would be very much appreciated! 任何帮助将不胜感激!
Additional information: 附加信息:
I'm using node v0.10.33 and express v4.x 我正在使用节点v0.10.33并表达v4.x
The mongo driver I am using is just the base javascript mongo driver for node. 我正在使用的mongo驱动程序只是node的基本javascript mongo驱动程序。
(found here: http://docs.mongodb.org/ecosystem/drivers/node-js/ ) (位于此处: http : //docs.mongodb.org/ecosystem/drivers/node-js/ )
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: 好的,我已经找到了将base64字符串转换为节点内的GUID格式的解决方案,需要将其转换为:
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);
});
You will have to convert the id in your GET method to a BinData() object just like it is shown in your sample document. 您必须将GET方法中的id转换为BinData()对象,就像示例文档中显示的那样。
In your current code it searches for _id matching a string (MH+t3q6PD0SxVR5z7/pzfw== in your sample). 在您当前的代码中,它搜索与字符串匹配的_id(在示例中为MH + t3q6PD0SxVR5z7 / pzfw ==)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.