返回mongoose模型函數的結果

[英]Return the result of a mongoose model function


I'm working on a Restful API with node.js and mongoose. I need to return an object with the results of a search. Here is my code:

我正在使用node.js和mongoose開發Restful API。我需要返回一個帶有搜索結果的對象。這是我的代碼:

var Get = function (criteria) {      
    var result;
    Users.findOne(criteria, function(err, res){
        console.log('Error: ' + err);
        console.log('Results: ' + res);
        result = err || !res ? err || errors['404']: res;
        console.log(result);
    });
    console.log('Final results: ' + JSON.stringify(result));
    return result;
};

Since I was having problems, I added those console.logs to watch where the result is lost. Here are the logs:

由於我遇到了問題,我添加了那些console.log來觀察結果丟失的位置。這是日志:

Final results: undefined Error: null Results: { //user... }

最終結果:未定義錯誤:null結果:{// user ...}

I need that result to be returned. How can I solve this?

我需要返回結果。我怎么解決這個問題?

1 个解决方案

#1


2  

This is one of the most asked questions in the history of the internet!

這是互聯網歷史上最常見的問題之一!

Since node is asynchronous you'll need to rewrite the function to return a callback or use something like promises.

由於節點是異步的,因此您需要重寫函數以返回回調或使用promises之類的東西。

Here it is with callbacks:

這是回調:

var Get = function (criteria, cb) {      
    return Users.findOne(criteria,cb);  
};

And then call it like:

然后稱之為:

Get({}, function(err, res){
  console.log(res);
});

Or you can use promises, here it is using the Q library

或者您可以使用promises,這里使用的是Q庫

var Get = function (criteria) {   

var deferred = Q.defer();
 Users.findOne(criteria,function(err, o){
       if (err) deferred.reject(err);
            deferred.resolve(o);
 });
 return deferred.promise;
}

And then call it like this:

然后像這樣調用它:

Get({}).then(function(res){console.log(res)});

The promise based version seems more complicated to me :).

基於承諾的版本對我來說似乎更復雜:)。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/04/17/be36929d6dacdd9b0237c81447b5305f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com