I went through this express tutorial. I was wondering if it is possible to outsource the following call to a separate function, as it is very very long?
employee_collection.db.bson_serializer.ObjectID.createFromHexString(id)
This is the whole file where the statement is called:
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmployeeProvider = function(host, port) {
this.db = new Db(
'node-mongo-employee',
new Server(host, port, {}),
{safe: true}
);
this.db.open(function(){});
};
...
// find an employee by id
EmployeeProvider.prototype.findById = function(id, callback) {
this.getCollection(
function(error, employee_collection) {
if( error )
callback(error)
else {
employee_collection.findOne(
{_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(id)},
function(error, result) {
if( error )
callback(error)
else
callback(null, result)
}
);
}
}
);
};
...
exports.EmployeeProvider = EmployeeProvider;
It's the controller of an express application. It's shortened, but should give you an idea of what it does. You can find the whole application on Github.
I tried
getid = function( employee_collection, id ) {
return employee_collection.db.bson_serializer.ObjectID.createFromHexString(id);
};
and called the function with
{_id: getid(employee_collection, id),
but I'm getting a very long ENOENT error with that one.
Presuming that you are working with the basic node.js mongodb driver here and that you have id essentially coming in as something like a request parameter, which means it's just a string and looks something like:
"53cfba87e248860d16e1f7e1"
Then the import you have used here:
var ObjectID = require('mongodb').ObjectID;
Gives you a direct function to use. Just do this:
employee_collection.findOne({ "_id": ObejctID(id) },function(err,result) {
// work in here
});
The ObjectID you are importing already implements this function.