2017-09-01 33 views
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分页,所以需要通过动态限制和抵消。

+1

'如果(ERR)res.send(ERR);'它不象调用回调或承诺的决心/拒绝它的分支出来。它实际上允许执行下一行代码。因此,可以使用'else'或'return',即if(err)return res.send(err);'停止进一步的执行。那么当然你需要解决你的其他错误。请注意,您没有检查'.count()'的错误状态。你真的应该。你真的应该使用promise和chaining,或者更好的是'async/await'和'try..catch'块。 –

回答

1

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