我怎样才能"缓存"我的Express.js视图和路由中使用的mongoDB / Mongoose结果

时间:2017-04-17 07:52:09

标签: mongodb express caching mongoose ejs

我想要实现的是 mongoDB / Mongoose 查询的缓存结果的某种方法,我可以在我的视图和路由中使用该查询。每当将新文档添加到集合中时,我都需要能够更新此缓存。由于函数是如何异步的,我不确定这是否可行以及是否可以这样做

这是我目前用于存储图库的内容,但是每次请求都会执行此操作。

app.use(function(req, res, next) {
  Gallery.find(function(err, galleries) {
    if (err) throw err;  
      res.locals.navGalleries = galleries;
      next();
  });
});

这用于获取图库名称,然后从动态生成的图库中显示在导航栏中。图库模型只设置了图库的名称 slug

这是我导航中 EJS 视图的一部分,该视图将值存储在下拉菜单中。

<% navGalleries.forEach(function(gallery) { %>
  <li>
    <a href='/media/<%= gallery.slug %>'><%= gallery.name %></a>
  </li>
<% }) %>

我正在处理的网站预计会有数十万个并发用户,所以我不想在不需要的情况下查询每个请求的数据库,只需更新它创建了一个新的画廊。

1 个答案:

答案 0 :(得分:3)

看看cachegoose。它允许您缓存所需的任何查询,并在每次创建新库时使该缓存条目无效。

你需要这样的东西:

const mongoose = require('mongoose');
const cachegoose = require('cachegoose');

cachegoose(mongoose); // You can specify some options here to use Redis instead of in-memory cache

app.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');
    });

    ...
});

虽然您可以在变量中手动缓存结果并在添加新图库时使该缓存无效,但我建议您先查看该包。