How can I store site configuration in MongoDB for a NodeJS Express App? How can I store site configuration in MongoDB for a NodeJS Express App? mongoose mongoose

How can I store site configuration in MongoDB for a NodeJS Express App?


Consider using express middleware for loading site config.

app.configure(function() {  app.use(function(req, res, next) {    // feel free to use req to store any user-specific data    return db.getSiteConfig(req.user, function(err, siteConfig) {      if (err) return next(err);      res.local('siteConfig', siteConfig);      return next();    });  });  ...});

Throwing an err is a realy bad idea because it will crash your application.So use next(err); instead. It will pass your error to express errorHandler.

If you already authenticated your user (in previous middleware, for example) and stored its data into req.user, you can use it to get the right config from db.

But be careful with using your getSiteConfig function inside of express middleware because it will pause express from further processing of the request until the data is received.

You shall consider caching siteConfig in express session to speedup you application. Storing session-specific data in express session is absolutely safe because there is no way for user to get access to it.

The following code demonstrates the idea of caching siteConfig in express sessionn:

app.configure(function() {  app.use(express.session({    secret: "your sercret"  }));  app.use(/* Some middleware that handles authentication */);  app.use(function(req, res, next) {    if (req.session.siteConfig) {      res.local('siteConfig', req.session.siteConfig);      return next();    }    return db.getSiteConfig(req.user, function(err, siteConfig) {      if (err) return next(err);      req.session.siteConfig = siteConfig;      res.local('siteConfig', siteConfig);      return next();    });  });  ...});