如何“缓存”要在 Express.js 视图和路由中使用的 mongoDB/Mongoose 结果

Chr*_*ort 6 caching ejs mongoose mongodb express

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

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

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

这用于获取画廊名称,然后将其显示在动态生成的画廊的导航栏中。画廊模型只设置了画廊的名称和一个slug

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

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

我正在开发的网站预计将获得数十万并发用户,因此如果不需要,我不想为每个请求都查询数据库,并且只要在创建新画廊时更新它。

Dan*_*ger 5

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

    ...
});
Run Code Online (Sandbox Code Playgroud)

尽管您可以在变量中手动缓存结果并在添加新画廊时使该缓存无效,但我建议您改为查看该包。