我最近开始使用 MongoDB 和 Node.js/Express,但在掌握一些概念方面仍然遇到困难。
请原谅新手问题。我找不到涵盖我想要学习的内容的现有答案。
这确实很简单,我只想在单个页面上输出两个单独的 mongo 查询的结果。我不需要以任何方式对数据进行分组或连接,我只需要在一页上显示每个查询的结果。
因此,我可以毫无问题地查询和显示单个查询,但我对第二个查询失败了,因为我的示例代码在 .js 文件中执行查询并呈现页面并将结果作为数组传递(如果我理解正确的话)所以
var collection = db.collection('photographers');
collection.find({}).toArray(function(err,result){
if(err){
console.log("Error retrieving records");
res.send(err);
}else if (result.length){
console.log("Success");
res.render('ptlist',{
"ptlist":result
});
}else{
res.send('No Documents');
}
db.close();
渲染我的 View “ptlist”并将结果传递到数组 ptlist 中。
我不知道如何对不同的集合执行另一个查询,并使结果数组也可在 View “ptlist”中使用。
如果有(简单的)例子,我们将不胜感激。否则,指向我可能在哪里找到一些评论良好的示例的指针也很酷。
抱歉,如果这是一个愚蠢的问题。对于这些东西来说,现在还为时过早。
最佳答案
根据您的代码,这将是最简单的解决方案。
这不太好,有一个回调 hell ,但它会起作用,假设 finalResult
具有可供 View 使用的结构。
为了让事情变得更好,您可以使用 async
例如。
或者 co
和 MongoDB ES6 yield
如their sample code .
var collection = db.collection('photographers');
collection.find({}).toArray(function(err,result){
var finalResult = {};
if(err){
console.log("Error retrieving records");
res.send(err);
} else if (result.length){
console.log("Success");
finalResult.plist = result;
collection.find({/* another query */}).toArray(function(err,result){
finalResult.anotherKey = result;
res.render('ptlist',{
"ptlist":finalResult
});
});
}else{
res.send('No Documents');
}
db.close();
});
关于javascript - 在一页上呈现两个 Mongo 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38056245/