Node.js页面请求速度慢,mongodb调用复杂,如何提高速度?

Node.js页面请求速度慢,mongodb调用复杂,如何提高速度?,node.js,mongodb,Node.js,Mongodb,我正在加载一个归档页面,其中包括搜索mongodb集合并在页面上显示大量文档。但是,执行此操作时,服务器调用需要一段时间。有没有加快速度的建议?我认为缓慢来自于这一行: Publication.find().limit(perPage).skip(perPage * page).sort('-date').exec(function (err, _publications) { 整版请求: app.get('/archive', function (req, res) { functio

我正在加载一个归档页面,其中包括搜索mongodb集合并在页面上显示大量文档。但是,执行此操作时,服务器调用需要一段时间。有没有加快速度的建议?我认为缓慢来自于这一行:

Publication.find().limit(perPage).skip(perPage * page).sort('-date').exec(function (err, _publications) {
整版请求:

app.get('/archive', function (req, res) {

  function timeConverter(UNIX_timestamp){
    var a = new Date(UNIX_timestamp);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var time = date + ' ' + month + ' ' + year;
    return time;
  }

  var perPage = 6
  pageParam = req.query['page']
  if (pageParam == null) {
    pageParam = 0
  }
  var page = Math.max(0, pageParam)

  // find all publications
  Publication.find().limit(perPage).skip(perPage * page).sort('-date').exec(function (err, _publications) {
    if (err) return console.error(err)

    for (id in _publications) { // convert date to text
      _publications[id].date = timeConverter( Number(_publications[id].date) )
    }

    Publication.find().limit(perPage).skip(perPage * (page + 1) ).count({},function(err, count) { // check if it's last page
      if (err) return console.error(err)

      if (count == 0) {
        nextPage = false
      } else {
        nextPage = page + 1
      }

      res.render(__dirname + '/../source/views/archive', {
        publications: _publications,
        nextPage: nextPage,
        prevPage: page - 1
      })

    })

    console.log('serving archive')
  })

})
执行.limitperPage.skipperPage*页面将影响您的响应时间。这现在被认为是最好的方法,因为mongo将首先扫描指定集合中以前的所有文档,然后跳过它们

一个更好的解决方案是获取所有id大于第一次响应中发送的文档。差不多

Publication.find({'_id': {'$gt': req.params.last_id}}, {}, { limit: perPage })
此处last_id是最后一个文档的id,此查询将返回该id之后的所有或指定数量的文档

此外,mongodb在其生成的id上应用索引,使用它进行搜索总是更快

方法缓慢的主要原因是因为使用了skip

cursor.skip方法通常代价高昂,因为它要求服务器在开始返回结果之前,从集合或索引的开头开始遍历以获取偏移量或跳过位置。随着偏移量(如上面的页码)的增加,cursor.skip将变得更慢,CPU占用也更大。对于较大的集合,cursor.skip可能会成为IO绑定

阅读更多

谢谢