【问题标题】:Multiple mongoDB queries in one router.get method nodejs一个router.get方法nodejs中的多个mongoDB查询
【发布时间】:2015-07-25 23:50:27
【问题描述】:

我想在 index.js 文件中的单个路由器方法中进行多个查询,如下所示,

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>

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

【问题讨论】:

标签: node.js


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多