2016-05-17 42 views
1

一直困住这个问题几个小时。下面的代码:节点JS mongoose查询不生成结果

router.route("/contact") 
    .get(function(req,res){ 
     var response = {}; 
     Contact.find({},function(err,data){ 
      if(err) { 
       response = {"error" : "Error fetching data"}; 
      } else { 
       response = {"message" : data}; 
      } 
      res.json(response); 
     }); 
    }) 

上面的查询产生与数据库中的所有联系人,但

router.route("/contact/department/:dept") 
    .get(function(req,res){ 
     var response = {}; 
     var arrDept = req.params.dept.split(","); 
     if(arrDept.length == 0){ 
      response = {"error": " Please enter Department keywords"}; 
     } 
     else{ 
      response = {}; 
      arrDept.forEach(function(currentValue){ 
       Video.find({dept: '/'+currentValue+'/i'}, function(err, data){ 
        if(err){ 
         response[currentValue] = "No data found"; 
        }else{ 
         response[currentValue] = data; 
        } 
       }); 
      }); 
     } 
     res.json(response); 
    }); 

此代码不会产生任何输出结果。

的代码进入else块foreach循环,但查询不产生任何结果,即使我修改查询到一个基本的像

Video.find({},function(err, data){ 
        if(err){ 
         response[currentValue] = "No data found"; 
        }else{ 
         response[currentValue] = data; 
        } 
       }); 

JSON仍会返回空白的响应。

PS:问题已被简化,因为这只是我在代码中遇到的实际问题的一个示例。找到答案后更新 。

回答

1

res.json(response);您的res.json(response);在您的MongoDB查询的回调之外,那就是您在查询的回调被实际执行之前编写回应,因此您的结果为空。

+0

感谢DAXaholic ....但我如何追加数据从循环的每个迭代到响应json对象? –

+0

要做到这一点,没有任何进一步的助手库,你可以例如使用结果在回调之外维护一个数组,并在回调中添加它,只要该数组的大小等于您的'arrDept',就知道您已获得所有结果。但说实话,使用诸如async.js之类的东西更容易和直接。有关我的意思的快速示例,请参阅https://github.com/caolan/async#map。 – DAXaholic

+0

thnx ...我终于用诺言解决了它。 var promise = Contact.find({dept:{$ in:arrayDept}})。exec(); \t \t \t promise.then(函数(resultJson){ \t \t \t \t res.json(resultJson); \t \t \t}); –

2
res.json(response) 

写在查询的外部,这就是为什么空白json得到返回。上述场景可以使用promise来解决,如下所示:

var promise = Contact.find({ dept: { $in: arrayDept }}).exec(); 
promise.then(function(resultJson) { res.json(resultJson); }); 

这可以用来执行数组中的所有查询并返回完整的json。