search

Home  >  Q&A  >  body text

mongodb - Node.js + Mongoose 让 Model.find 方法同步执行

我在用 Node.js + Mongoose + MongoDB 开发一个小程序,其中有一个操作是这样的:

function get( query ){
    query = query||null;
    if( query === null ){
        return this.model.find( {}, function( err, docs ){
            return docs;
        });
    }else{
        return this.model.find( query, function( err, docs ){
            return docs;
        }
    }
}

目标:get 是我用来读取 Collection 里面的文档的,query 是查询条件,如果没有传入查询条件,则返回整个 Collection;如果传入了查询条件,则按条件查询。

错误:因为 this.model.find方法是异步的,find返回查询结果之前,get函数已经return,所以我总是得到undefined

请问有什么办法能让get得到find的返回值吗?

巴扎黑巴扎黑2795 days ago639

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 11:09:16

    The entire design idea of ​​nodejs is asynchronous, don’t write with synchronous thinking.

    var url=require('url');
    function get(query,callback){
        query=query||{};
        this.model.find(query,callback);
    }
    
    httpServer.on('request',function(req,res){
        var query=url.parse(req.url, true).query;
    
        get(query,function(err,doc){
            if(err){
                res.end(err);
                return;
            }
    
            res.end(doc)
        })
    })
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:09:16

    It is best to use callbacks for asynchronous requests

    function get( query,callback ){
        query = query||{};
        this.model.find( query, function( err, docs ){
             callback(null, docs);
        });
    }
    

    When query is empty, the entire collection is returned

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:09:16

    You can use libraries such as Q and Step to force query synchronization.

    In fact, most people do need synchronization methods when writing tests. I also specifically asked the author of Mongoose, but he felt it was not necessary. . .

    reply
    0
  • Cancelreply