Take the 2-minute tour ×

I'm writing a nodeJS REST api server with express for the forwarding part. Now part of what the server will do is backup different kinds of data, and there will be requests for backing up certain types of data I'll support and all of the requests that I support. To save on code duplication I was thinking of just calling all of the backup-individual-types-of-data functions from the request that deals with backing up everything.

Individual type of data backup functions.

function verifyUserId(req, res, functionToGoTo) {

    req.mongoClient.collection('syncServiceAccounts', checkForAccount = function (err, collection) {
        collection.find({_id:req.objectID.createFromHexString(req.params.syncServiceUser)}).toArray(function (err, results) {
            if (results.length != 0) {
                functionToGoTo(req, res, results[0].share_key);
            } else {
    //Set all server contacts as on device
exports.syncServiceContactsSync = function (req, res) {
    verifyUserId(req, res, syncServiceContactsSync, sendContactsSyncResponse);
    //verifyUserId(req, res, syncServiceContactsSync);
function syncServiceContactsSync(req, res, shareKey, callback) {
//function syncServiceContactsSync(req, res, shareKey) {
    jsonObject = (req.body);
    var jsonResponse = new Array();

    req.mongoClient.collection('syncService_Contacts', insertSyncServiceUser = function (err, collection) {

        for (var i = 0; i < jsonObject.length; i++) {
            jsonObject[i].share_key = shareKey;

        collection.find({share_key:shareKey}).toArray(function (err, results) {
            //res.json(jsonResponse, 200);
function sendContactsSyncResponse() {
    res.json(jsonResponse, 200);

And in the following function i'd like to be able to just call all the individual backup type.

   //Set all server items as on the device
exports.syncServiceSync = function (req, res) {
    contactsObj = new Contacts();


I could just call the exported syncServiceContacsSync and it's equivalents for each type of data, but then i'd verify the userID for each new type of data, when I could do it once from the syncServiceSync. Is there a way to do that, and tell the syncServiceContactsSync what to do once it has inserted the data? Preferably it would go to a function together with the jsonResponse where I'd cascade it into the next data type.

Also to note that the two blocks of files are in different files in the same folder.

EDIT: To make it easier to understand. I have a system that backs up data type A, B, C, into their own mongo collections. I have another collection for the registered users for my app. In terms of requests, I have some that deal with backing up A, B, C individually and one that deals with all of them for a particular user account. In the one that deals with all of them, I thought it would be a good idea to use the functions that back up A, B, C so I don't have code duplication. As a result, what I'd kind want (but it might end up implemented differently) is that when I want to backup all of the data types, then I'd simply call the one that deals with A, then cascade into the one that deals with B, then the one with C. Besides simply cascading into each function, I'd also like to cascade some data (resource ID, so the IDs of the As, into the function that deals with Bs, then the IDs of A and B into the one that deals with C, and then into a final function that returns all of these IDs). The problem that I have is that the way the code is written now, every time I'd cascade, I'd recheck to see if I can find the user in the user collection, and that's just kinda stupid.

share|improve this question

1 Answer 1

I'm not quite sure I fully understand your question, but have you looked into Route Middleware that's available with Express routes? More info is available at http://expressjs.com/guide.html#route-middleware.

It basically allows you to insert logic into the request pipeline so that you can define the logic in one place and use it with multiple routes.

function loadUser(req, res, next) {
  // You would fetch your user from the db
  var user = users[req.params.id];
  if (user) {
    req.user = user;
  } else {
    next(new Error('Failed to load user ' + req.params.id));

app.get('/user/:id', loadUser, function(req, res){
  res.send('Viewing user ' + req.user.name);
share|improve this answer
If it does, please make sure to mark this as the answer to your question. –  Bill Feb 15 '12 at 19:44
Yep, will do, don't worry. –  Alex B Feb 15 '12 at 21:05
@Bill It's not clear from your example how the next(new Error(...)) is going to be funneled to the app.get('/user/:id') function. How does one get to retrieve the error passed to next()? It would be good to see this mentioned in the example. –  titusmagnus Sep 28 '13 at 15:55

Your Answer


