gpt4 book ai didi

node.js - 在 mongodb select 中使用偏移量和限制

转载 作者:行者123 更新时间:2023-12-02 03:01:20 26 4
gpt4 key购买 nike

这是我在 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 进行分页,所以需要通过动态限制和偏移。

最佳答案

you have to stop your async code using return keyword or handle the proper condition flow will slove you issue {I am using return below}

  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);
});
});

other wise maintain the Condition controll flow

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);
});
});

关于node.js - 在 mongodb select 中使用偏移量和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com