在mongodb选择中使用偏移和限制

时间:2017-09-01 13:00:50

标签: node.js express mongoose

以下是我在meanstack中使用的代码来获取有限的数据

apiRouter.get('/pagination_posts', function(req, res){
    console.log(req.params)       // getting object having value for limit and offset
    Post.count({},function(err,count){
        console.log(count)     // total number of records
        Post.find({}, function(err, posts){
            if (err) res.send(err);
            res.json({total:count,posts:posts});
        }).skip(req.query.offset).limit(req.query.limit);
    });
});

获取以下错误:

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/Volumes/E/simerjit/fwrkdeploy/node_modules/express/lib/response.js:718:10)
    at ServerResponse.send (/Volumes/E/simerjit/fwrkdeploy/node_modules/express/lib/response.js:163:12)
    at ServerResponse.json (/Volumes/E/simerjit/fwrkdeploy/node_modules/express/lib/response.js:249:15)
    at /Volumes/E/simerjit/fwrkdeploy/server/api/posts.js:29:9
    at /Volumes/E/simerjit/fwrkdeploy/node_modules/mongoose/lib/model.js:3822:16
    at /Volumes/E/simerjit/fwrkdeploy/node_modules/kareem/index.js:213:48
    at /Volumes/E/simerjit/fwrkdeploy/node_modules/kareem/index.js:131:16
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

如果我在这里使用静态值}).skip(0).limit(10);,它工作正常,但我想使用此api进行分页,因此需要传递动态限制和偏移量。

1 个答案:

答案 0 :(得分:1)

  

你必须使用return关键字停止你的异步代码或处理正确的条件流将解决你的问题{我正在使用以下返回}

  apiRouter.get('/pagination_posts', function(req, res){
        console.log(req.params)       // getting object having value for limit and offset
        Post.count({},function(err,count){
            console.log(count)     // total number of records
            Post.find({}, function(err, posts){
                if (err) return res.json(err);  
               return res.json({total:count,posts:posts});
            }).skip(req.query.offset).limit(req.query.limit);
        });
    });
  

其他明智的维护条件控制流程

apiRouter.get('/pagination_posts', function(req, res){
            console.log(req.params)       // getting object having value for limit and offset
            Post.count({},function(err,count){
                console.log(count)     // total number of records
                Post.find({}, function(err, posts){
        if (err) ? res.json(err):  res.json({total:count,posts:posts});
                }).skip(req.query.offset).limit(req.query.limit);
            });
        });