如何从 find 方法返回 Mongoose 结果? [英] How to return Mongoose results from the find method?
问题描述
我能找到的关于用猫鼬结果来渲染页面的所有内容都说要这样做:
Everything I can find for rending a page with mongoose results says to do it like this:
users.find({}, function(err, docs){
res.render('profile/profile', {
users: docs
});
});
我怎样才能从查询中返回结果,更像这样?
How could I return the results from the query, more like this?
var a_users = users.find({}); //non-working example
这样我就可以在页面上发布多个结果?
So that I could get multiple results to publish on the page?
喜欢:
/* non working example */
var a_users = users.find({});
var a_articles = articles.find({});
res.render('profile/profile', {
users: a_users
, articles: a_articles
});
这能做到吗?
推荐答案
您正在尝试强制使用同步范式.就是不行.node.js 是单线程的,在大多数情况下——当 io 完成时,执行上下文被产生.信令通过回调进行管理.这意味着您可以使用嵌套回调、命名函数或流控制库来使事情看起来更漂亮.
You're trying to force a synchronous paradigm. Just does't work. node.js is single threaded, for the most part -- when io is done, the execution context is yielded. Signaling is managed with a callback. What this means is that you either have nested callbacks, named functions, or a flow control library to make things nicer looking.
https://github.com/caolan/async#parallel
async.parallel([
function(cb){
users.find({}, cb);
},
function(cb){
articles.find({}, cb);
}
], function(results){
// results contains both users and articles
});
这篇关于如何从 find 方法返回 Mongoose 结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!