如何从find方法返回Mongoose结果? [英] How to return Mongoose results from the find method?

查看:633
本文介绍了如何从find方法返回Mongoose结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以找到的任何可以使用mongoose结果重绘页面的内容都可以这样做:

  users.find({ },function(err,docs){
res.render('profile / profile',{
users:docs
});
});

如何从查询中返回结果,更像这样?

  var a_users = users.find({}); //非工作示例

所以我可以在页面上获得多个结果发布? p>

喜欢:

  / *非工作示例* / 
var a_users = users.find({});
var a_articles = articles.find({});

res.render('profile / profile',{
users:a_users
,articles:a_articles
});

可以这样吗?

解决方案

你试图强制一个同步的范例。不行在大多数情况下,node.js是单线程的,当io完成时,执行上下文被生成。信令由回调管理。这意味着你有嵌套回调,命名函数或流控制库,使事情更好看。



https://github.com/caolan/async#parallel

  async.parallel([
function(cb){
users.find({},cb);
},
function(cb){
articles.find({},cb);
}
],function(results){
//结果包含用户和文章
});


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?

like:

/* non working example */
var a_users    = users.find({});
var a_articles = articles.find({});

res.render('profile/profile', {
      users:    a_users
    , articles: a_articles
});

Can this be done?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆