我在用 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
的返回值吗?
迷茫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)
})
})
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
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. . .