2
這裏是我正在使用meanstack來獲取有限的數據使用偏移和限制在MongoDB中選擇
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分頁,所以需要通過動態限制和抵消。
'如果(ERR)res.send(ERR);'它不象調用回調或承諾的決心/拒絕它的分支出來。它實際上允許執行下一行代碼。因此,可以使用'else'或'return',即if(err)return res.send(err);'停止進一步的執行。那麼當然你需要解決你的其他錯誤。請注意,您沒有檢查'.count()'的錯誤狀態。你真的應該。你真的應該使用promise和chaining,或者更好的是'async/await'和'try..catch'塊。 –