【问题标题】:Mongoose, AngularJS, NodeJS猫鼬,AngularJS,NodeJS
【发布时间】:2014-10-06 23:05:24
【问题描述】:

我正在使用 MongoDB 数据库。 对于前面的AngularJS

另外,我正在使用 Mongoose

我有:

app.get("/images", function(req, res) {
    mongoose.model('Image').find(function (err, images) {
        res.send(images);
    });
});
app.listen(3000);

当我去:http://localhost:3000/images时它工作正常

然后:

<div ng-repeat="photo in photos">
   <!-- My Data List -->
   <h3>{{photo.name}}</h3>
</div>

到这里为止,一切都很好。

但是我将有成千上万的数据要显示。 所以我需要像前面的“无限滚动”之类的东西,而且我需要用查询范围或分页来限制 API http://localhost:3000/images ???

我如何才能继续使用大量数据

谢谢!

【问题讨论】:

    标签: node.js angularjs mongoose


    【解决方案1】:

    如果数据量很大,您可能不想一次加载所有数据。 首先,我会做这样的事情来限制您为每个请求获得的条目数。

    app.get("/images", function(req, res) {
        var query = mongoose.model('Image').find({})
                    .limit(req.query.numberOfItems)
                    .skip(req.query.index)
    
        query.exec(function (err, images) {
            res.send(images);
        });    
    });
    app.listen(3000);
    

    在客户端上,您应该决定在需要时动态加载更多数据。

    这在一定程度上取决于您希望用户体验如何,例如拥有不同的页面,并且在您打开下一页或用户进一步向下滚动时加载更多数据等。

    【讨论】:

    • 感谢您的帮助!
    【解决方案2】:

    使用mongoose-paginate 在猫鼬中使用服务器端分页并限制您的查询输出。在角度使用angular-ui pagination 中包含分页的方法相同。如果你想使用无限滚动,那么在角度使用ngInfiniteScroll

    希望这会有所帮助。

    【讨论】:

    • 谢谢我去看看!
    【解决方案3】:

    您可以使用 mongoose Query API 指定搜索条件:http://mongoosejs.com/docs/queries.html

    您可以使用where() 指定分页标准,例如where({id: {$gt: page}})(假设您使用某种自动递增的id)和limit() 指定您的页面大小,例如limit(10)

    每次向服务器查询其他页面时,都需要在 URL 中提供条件:/images?page=1。每次获取页面时,此条件应增加 10。

    条件可以是任何表示数据顺序的东西,可以是 ID、时间戳或其他任意值。

    【讨论】:

      【解决方案4】:

      限制猫鼬中的数据:

      mongoose.model('Image').limit(10).exec(function(err, images){
        // get the images....
      }); // this will only return 10 images
      

      在 Angular 中,您可以使用 limitTo 过滤器:

      <div ng-repeat="photo in photos | limitTo: 10 ">
         <!-- My Data List -->
         <h3>{{photo.name}}</h3>
      </div>
      

      现在您可以从这里学习如何分页或无限滚动。 (网上有各种关于这个话题的tuts)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-18
        • 2021-06-01
        • 2013-06-21
        • 2016-02-05
        • 2021-03-17
        • 1970-01-01
        • 2014-11-17
        • 2015-09-06
        相关资源
        最近更新 更多