简体   繁体   English

有什么办法可以让后端不必在 Node JS 中多次向数据库请求数据?

[英]Is there any way that backend does not have to request database for data multiple times in Node JS?

For eg.例如。

I have 20000 meals in database我在数据库中有 20000 顿饭

The first request comes from frontend: I have to display 10 meals only,第一个请求来自前端:我必须只显示 10 餐,

So I send a request to the backend to fetch 1000 meals from the database, and then from those 1000 meals I display the first 10 meals only(meal1, meal2,..., meal10).所以我向后端发送一个请求,从数据库中获取 1000 顿饭,然后从这 1000 顿饭中我只显示前 10 顿饭(饭 1、饭 2、...、饭 10)。

Then the page is scrolled until it needs to display more meals然后页面滚动,直到需要显示更多餐点

The second request comes:第二个请求来了:

Now when the frontend asks 11-20 meals from backend, the backend should not go to the database for this request, it should display these data from the 1000 meals that the backend fetched from database in 1st request现在,当前端向后端询问 11-20 餐时,后端不应该为此请求去数据库,它应该显示后端在第一个请求中从数据库中获取的 1000 餐中的这些数据

Just curious to know if this is possible...只是想知道这是否可能......

Thanks for your time...谢谢你的时间...

Meal.aggregate([{
        $skip: (req.query.page - 1) * 10,
        },{$lookup: {
            from: 'restaurants',
            localField: 'restaurantID',
            foreignField: '_id',
            as: 'restaurant'
        }
        }, {
            $replaceRoot: {newRoot: {$mergeObjects: [{$arrayElemAt: ["$restaurant", 0]}, "$$ROOT"]}}
        }, {
            $addFields: {
                returnObject: {
                    $or: [
                        {$regexMatch: {input: '$mealName', regex: search}}, 
                        {$regexMatch: {input: '$name', regex: search}}
                    ]
                }
            }
        }, {
            $match: {'returnObject': {$ne: false}, 'nutrient': {$ne: {}}, mealPrice: {$lt: req.query.upperPrice, $gt: req.query.lowerPrice}}
        }, {
            $project: { mealName: 1, name: 1, nutrient: 1, mealPrice: 1}
        }, {
            $limit: 5000
        }]);

This is the query that I am using to get data from the database,这是我用来从数据库中获取数据的查询,

After I received data, I need to perform some calculations which are going to change from user to user.收到数据后,我需要执行一些计算,这些计算会因用户而异。

Then I will apply pagination on the calculated data.然后我将对计算的数据应用分页。

So the problem is when the second request comes, my current system does all the calculations and then it displays the next 10 data.所以问题是当第二个请求到来时,我当前的系统完成所有计算,然后显示接下来的 10 个数据。

So I need to somehow save those calculations that I did when the first request arrived.所以我需要以某种方式保存我在第一个请求到达时所做的计算。

Using caching framework like redis.使用像redis这样的缓存框架。 Tweak your scenario a little since caching is costly.. redis is pretty easy to setup and run.稍微调整一下你的场景,因为缓存成本很高.. redis 很容易设置和运行。

当然有可能,您可能正在谈论分页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM