title: How can I "cache" a mongoDB/Mongoose result to be used in my Express.js views and routes
body: <p>What I'm trying to achieve is some sort of way to <strong>cache results</strong> of a <strong>mongoDB/Mongoose</strong> query that I can use in my views and routes. I'd need to be able to update this cache whenever a new document is added to the collection. I'm not sure if this is possible and if it is then how to do it, due to how the functions are asynchronous</p>
  
  <p>This is currently what I have for storing the galleries, however this is executed with every request.</p>
  
  <pre><code>app.use(function(req, res, next) {
    Gallery.find(function(err, galleries) {
      if (err) throw err;  
        res.locals.navGalleries = galleries;
        next();
    });
  });
  </code></pre>
  
  <p>This is used to get gallery names, which are then displayed in the navigation bar from a dynamically generated gallery. The gallery model is setup with just a <strong>name</strong> of the gallery and a <strong>slug</strong></p>
  
  <p>and this is part of my <strong>EJS</strong> view inside of my navigation which stores the values in a dropdown menu.</p>
  
  <pre><code>&lt;% navGalleries.forEach(function(gallery) { %&gt;
    &lt;li&gt;
      &lt;a href='/media/&lt;%= gallery.slug %&gt;'&gt;&lt;%= gallery.name %&gt;&lt;/a&gt;
    &lt;/li&gt;
  &lt;% }) %&gt;
  </code></pre>
  
  <p>The website I'm working on is expected to get hundreds of thousands of concurrent users, so I don't want to have to query the database for every single request if not needed, and just update it whenever a new gallery is created.</p>