2015-05-14 67 views
1

我想有多个查询在一台路由器的方法在我的index.js文件如下,多的MongoDB查询的NodeJS

router.get('/users', function(req, res) { 
var db = req.db; 
var users = db.get('users'); 
var col_name=req.query.colname; 
var col_value=req.query.colvalue; 
var query={}; 
query[col_name]=col_value;  
console.log(col_name);  
console.log(col_value);  
console.log(query); 

//using this i would like to populate my dropdown list 

users.distinct('symbol',{limit: 10000},function(e, syms){  
res.send('users', {  
title: 'usersSym',  
'usersSym': syms   
}); 
}); 

// using this I would populate a table in html 

users.find(query,{limit: 10000},function(e, docs){ 
res.render('users', { 
title: 'Users', 
'users': docs 
}); 
}); 
}); 

在我.ejs文件我试图做到以下几点:

<html> 
<head> 
//drop down list populating with first query 
<select id="selected" name="colvalue" > 
<option value="">--Select--</option> 
<% usersSym.forEach(function(usersym) { %> 
<option value="<%= usersym.symbol %>"><%= usersym.symbol %></option> 
<% }); %> 
</select> 
//Table populating with second query 
<table > 
<tr > 
<th>Symbol</th> 
<th>Order_id</th> 
</tr> 
<tr> 
<% users.forEach(function(user) { %> 
<td ><%= user.symbol %></td> 
<td><%= user.order_id %></td> 
</tr> 
<% }); %> 
</table> 
</body> 
</head> 
</html> 

但没有运气。想知道我是否在正确的方向前进。如果不是,请以正确的方式引导我。

+0

看看[这个答案在这里(http://stackoverflow.com/questions/29825166/how-to-return-multiple-mongoose-collections-in-one-get-request/ 29825572#29825572)。它可能会帮助你。 –

回答

1

// 1st fetch symbol users.distinct('symbol',{limit: 10000},function(e, syms){ // 2nd fetch [users] users.find(query,{limit: 10000},function(e, docs){ res.render('users', { usersSym: syms, users: docs } ); }); }); // P.S. do not forget to check on error on each callback

+0

谢谢,它工作 – sasidharan

1

您只能将数据发送回客户端一次。一种方法是按顺序完成所有这些数据库查询,然后发送所有数据。另一个可能是按照你的方式来做,检查所有数据库查询的状态,如果全部完成,则发送数据。