S.Will
S.Will

Reputation: 400

Effective way to get data that's needed on all pages

I'm using nodejs and express and I have a navigation menu that is built using data that is in mongodb currently I'm just making a call to the database to get a list of companies and passing that back inside each route. There doesn't seem to be a way to store this information in localstorage client side. So I"m wondering what is the most effective way to handle this situation. Sample of my code

admin.get('/', function(res, resp){
    mongodb.connect(url, function(err, db){  
        var collection = db.collection('companies')
        collection.find({}).toArray(function(err, companies){
            res.render('adminview', {companies:companies})//once the page is rendered I would like to save the company list to localstorage.
         })
    })
})  
admin.get('/:company', function(res, resp){
/* repeating code from above because I need this list */
     mongodb.connect(url, function(err, db){  
        var collection = db.collection('companies')
        collection.find({}).toArray(function(err, companies){
            /* more code to do stuff to render the company page */
            res.render('companyadminview', {companies:companies, company:company})
        }) }) 

I could be going about this the wrong way I'm new to web development this feels wrong to me but can't figure out a different way.

Upvotes: 0

Views: 51

Answers (1)

Paul
Paul

Reputation: 36319

So, first off you should be able to store it in localstorage or sessionstorage just fine, unless you're targeting browsers that don't support it.

That said, I think it's best not to, as the fact that you're storing it in the DB implies that it changes with enough frequency that you will get buggy clientside behavior if you cache it there for too long.

Instead, I'd just setup a middleware and attach it to the locals object on a per request basis, unless you want to do some kind of cache on the server:

app.use(function(req, res, next) {
  mongodb.connect(url, function(err, db){  
        if (err) return next(err);
        var collection = db.collection('companies')
        collection.find({}).toArray(function(err, companies){
            if (err) return next(err);
            res.locals.companies = companies;
            next();
         });
    });
});

Upvotes: 1

Related Questions