Mongo and Node.js: Finding a document by _id using

2019-05-22 13:53发布

问题:

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.

In mongo the _id is currently stored like this (as a GUID):

{
"_id" : new BinData(3, "MH+t3q6PD0SxVR5z7/pzfw=="), 
"companyname" : "TestCompany",
"databasename" : "TestDataBase",
}


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

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?

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:

I'm using node v0.10.33 and express v4.x

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

回答1:

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


回答2:

You will have to convert the id in your GET method to a BinData() object just like it is shown in your sample document.

In your current code it searches for _id matching a string (MH+t3q6PD0SxVR5z7/pzfw== in your sample).