我在用 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
的返回值吗?
The entire design idea of nodejs is asynchronous, don’t write with synchronous thinking.
It is best to use callbacks for asynchronous requests
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. . .