延迟加载/更多数据滚动Mongoose / Nodejs [英] Lazy Loading/More Data Scroll in Mongoose/Nodejs

查看:66
本文介绍了延迟加载/更多数据滚动Mongoose / Nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用mongoose在滚动上实现延迟加载/更多数据。我想一次加载10个帖子,但我不确定如何最好地加载查询中的下10个元素。

I was wondering how to implement lazy loading/more data on scroll with mongoose. I want to load 10 posts at a time, but I'm not sure how to best load the next 10 elements in a query.

我目前有:

var q = Post.find().sort("rating").limit(10);

加载具有最高评级的10个帖子。我如何为下一个 10个帖子做这件事?

To load the 10 posts with the highest "rating". How do i go about doing this for the next 10 posts?

推荐答案

一般概念分页是使用 .skip(),它基本上跳过已经检索过的结果,所以你基本上可以这样做:

The general concept of "paging" is to use .skip() which essentially "skips" over the results that have already been retrieved, so you can essentially do this:

var q = Post.find().sort( "rating" ).skip(10).limit(10);

但实际上,你可以想象当你得到一些页面时,这会大大减慢因此。你真的想要更聪明的东西。本质上,这是一个范围查询,您希望获得比检索到的最后一组结果更高(或更低,如果下降)的结果。因此,给定 5 的最后一个值,然后比你要做的更多:

But really, as you can imagine this is going to slow down considerably when you get a few "pages" in. So you really want something smarter. Essentially this is a "range query" where you want to grab higher (or lower if descending ) results than the last set of results retrieved. So given the last value of 5 then for greater than you would do:

var q = Post.find({ "rating": { "$gt": 5 } }).sort( "rating" ).limit(10);

看起来没关系,但确实还有问题。如果下一个页面还包含评分为5的结果怎么办?此查询将跳过这些查询并且永远不会显示它们。

Looks Okay, but really there is still a problem. What if the next "page" also contained results with a rating of 5? This query would skip over those and never display them.

聪明的做法是保留所有 _id 文档中的值,因为它们是唯一键。基本上应用相同类型的东西,除非这次你确保你没有在新的页面中包含上一页的结果。 $ nin 运营商帮助:

The smart thing to do is "keep" all of the _id values from the document since they are unique keys. Basically apply the same sort of thing, except this time you make sure you are not including the results from the previous page in your new one. The $nin operator helps here:

var q = Post.find({ "rating": { "$gte": 5 }, "_id": { "$nin": seenIds } })
    .sort( "rating" ).limit(10);

seenIds 是否只是最后一页结果或更多取决于你要排序的值的密度,当然你需要将它们保存在会话变量或其他东西中。

Whether the seenIds is just the last page of results or some more depends on the "density" of the value you are sorting on, and of course you need to "keep" these in a session variable or something.

但是尝试对此进行调整,因为范围查询通常是您的最佳表现结果。

But try to adapt this, as range queries are usually your best performance result.

这篇关于延迟加载/更多数据滚动Mongoose / Nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆