将参数传递给猫鼬嵌套查询

时间:2018-11-02 09:47:03

标签: javascript mongodb express mongoose mongodb-query

我不明白为什么我会收到504个网关超时。

app.get("/api/exercise/log", function(req,res) {
  let userId = req.query.userId;
  let from = req.query.from;
  let to = req.query.to;
  let limit = req.query.limit;
  console.log("limit1 " + limit);
  User.findById(userId).exec(function (err,data) {
    console.log("limit2 " + limit);
    if (err) return err;
    Exercise.find({userId: userId}).limit(limit).exec(function (err2,data2) {
      console.log("limit3 " + limit);
      if (err2) return err2;
      let logArr = [];
      logArr.push(data2);
      let total = logArr[0].length;
      let answer = Object.assign({}, data._doc, {log: logArr}, {total: total});  
      res.json(answer);
    })    
  })  
})

我的网址以log?userId = 555&limit = 2结尾。所有控制台日志(limit1,limit2,limit3)都会按预期打印“ 2”,但是我没有得到任何结果,只有超时。如果我更改该行以手动输入限制,例如

Exercise.find({userId: userId}).limit(2).exec(function (err2,data2) {

一切正常,我得到正确数量的结果。这是怎么回事?

1 个答案:

答案 0 :(得分:0)

使用parseInt将限制更改为数字,并检查该值是否可以转换为数字。

app.get("/api/exercise/log", function(req,res) {
  let userId = req.query.userId;
  let from = req.query.from;
  let to = req.query.to;
  let limit = 10;
  if(!isNaN(req.query.limit)){
      limit = parseInt(req.query.limit);   // use limit from query params if it is a valid number
  }
  console.log("limit1 " + limit);
  User.findById(userId).exec(function (err,data) {
    console.log("limit2 " + limit);
    if (err) return err;
    Exercise.find({userId: userId}).limit(limit).exec(function (err2,data2) {
      console.log("limit3 " + limit);
      if (err2) return err2;
      let logArr = [];
      logArr.push(data2);
      let total = logArr[0].length;
      let answer = Object.assign({}, data._doc, {log: logArr}, {total: total});  
      res.json(answer);
    })    
  })  
})