How can I "cache" a mongoDB/Mongoose result to be used in my Express.js views and routes
Take a look at cachegoose
. It will allow you to cache any query you want and invalidate that cache entry each time a new gallery is created.
You will need something like this:
const mongoose = require('mongoose');const cachegoose = require('cachegoose');cachegoose(mongoose); // You can specify some options here to use Redis instead of in-memory cacheapp.get(function(req, res, next) { ... Gallery .find() .cache(0, 'GALLERY-CACHE-KEY') .exec(function(err, galleries) { if (err) throw err; res.locals.navGalleries = galleries; next(); }); ...});app.post(function(req, res, next) { ... new Gallery(req.body).save(function (err) { if (err) throw err; // Invalidate the cache as new data has been added: cachegoose.clearCache('GALLERY-CACHE-KEY'); }); ...});
Although you could do something simpler caching the results manually in a variable and invalidating that cache when new galleries are added, I would advise you to take a look at that package instead.