【问题标题】:Mongodb get results asynchronouslyMongodb 异步获取结果
【发布时间】:2015-10-21 13:58:33
【问题描述】:

这是我的操作,它将从用户集合中获取所有用户

app.post('/login', function(req,res,next){
    users = self._db.get('users', {})
})

这是我在数据库类中的函数

this.get = function( col, opt )
    {   
        var result = [],
            opt    = opt || {};

        query  = db.collection(col).find( opt );

        query.each( function(err, doc) 
        {
            console.log( doc );
            if( doc != null )
            {
                result.push( doc );
            }
        });

        return result;
    };  

当我记录用户对象时,它会返回空数组,但是当我在函数中记录每个文档时,它会成功运行

问题是如何异步获取结果?

【问题讨论】:

标签: javascript node.js mongodb asynchronous express


【解决方案1】:

使用 async 之类的库来放置回调,当每个循环完成对所有文档的迭代时,可以返回结果数组。

Async 'each' function

【讨论】:

    【解决方案2】:

    您缺少 回调 功能。由于 Node.js 在设计上是异步的,所有 I/O 操作都需要回调。

    回到你的例子,我建议你使用monk并做这样的事情:

    var db = require('monk')('localhost/mydb');
    var users = db.get('users');
    
    app.post('/login', function(req, res) {
    
      users.find({}, function(err, data) {
    
        // remember to handle error here, for example;
        // if (err) return res.send('error');      
    
        res.json(data);  
    
      });
    
    });
    

    基本上,您缺少的回调是users.find 函数的第二个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-28
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多