在MongoDB查询中使用偏移量和限制。

3

这里是我在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
如果(错误)res.send(err);这不像调用回调或承诺resolve/reject一样,其中它会分支出来。它实际上允许下一行代码执行。因此,使用else或return即if(err)return res.send(err);来停止进一步的执行。然后当然你需要修复其他错误。请注意,您没有检查.count()上的错误状态。你真的应该。你应该使用承诺和链接,或者更好的是async/await和一个try..catch块。 - Neil Lunn
1个回答

1
你需要使用return关键字停止异步代码,或者处理正确的条件流程来解决你的问题{我在下面使用了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);
            });
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接