mongodb - Node.js + Mongoose 让 Model.find 方法同步执行
巴扎黑
巴扎黑 2017-04-17 11:07:16
0
3
630

我在用 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的返回值吗?

巴扎黑
巴扎黑

reply all(3)
迷茫

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)
    })
})
左手右手慢动作

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

洪涛

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. . .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template