2016-09-23 77 views
0

我一直在學習q的承諾,並試圖建立一些模擬API來實現其功能的forEach功能,而這樣做我碰到下面的錯誤來了,麻煩在使用Node.js的

Enterprise.forEach is not a function

我API代碼如下,

var mongoose = require('mongoose'); 
 

 
var Enterprise = mongoose.model('Enterprise_gpy'); 
 
var q = require('q'); 
 

 
var displayEnterprise = function(req, res) { 
 

 
    function displayEnterpriseName() { 
 

 
    var deferred = q.defer(); 
 

 
    Enterprise.forEach(function(err, doc) { 
 

 
     if (err) { 
 
     console.log('Error Finding Files'); 
 
     deferred.reject(err); 
 
     } else { 
 
     var name = Enterprise.enterprise_name; 
 

 
     deferred.resolve({ 
 
      name: name 
 
     }); 
 
     } 
 

 
     return deferred.promise; 
 
    }); 
 
    } 
 

 
    function displayEnterpriseEmail() { 
 

 

 
    var deferred = q.defer(); 
 

 
    Enterprise.forEach(function(err, doc) { 
 

 
     if (err) { 
 
     console.log('Error Finding Files'); 
 
     deferred.reject(err); 
 
     } else { 
 
     var email = Enterprise.enterprise_email; 
 

 
     deferred.resolve({ 
 
      email: email 
 
     }); 
 
     } 
 

 
     return deferred.promise; 
 
    }); 
 
    } 
 
    q.all([ 
 
     displayEnterpriseName(), 
 
     displayEnterpriseEmail() 
 
    ]) 
 
    .then(function(success) { 
 
     console.log(500, success); 
 
    }) 
 
    .fail(function(err) { 
 
     console.log(200, err); 
 
    }); 
 
} 
 
module.exports = { 
 

 
    displayEnterprise: displayEnterprise 
 
}

回答

2

在你的代碼Enterprise是貓鼬的架構,所以當你儘量做到循環使用的forEach然後起身

Enterprise.forEach is not a function

可以Enterprise.find()後使用forEach。所以使用

Enterprise.find({}, function(err, docs) { 
    if (err) { 
    console.log('Error Finding Files'); 
    deferred.reject(err); 
    } else { 
    var names = []; 
    docs.forEach (function(doc) { 
     var name = doc.enterprise_name; 
     names.push(name);// pushed in names array 
     //..... 
    }); 
    deferred.resolve({ 
     names: names 
    }); // return all names 
    } 
}); 

,而不是

Enterprise.find().forEach 

,並應使用var name = Enterprise.enterprise_name;

var email = doc.enterprise_email;而不是var email = Enterprise.enterprise_email;

var name = doc.enterprise_name;代替

+0

錯誤仍然存​​在,類型錯誤:Enterprise.find(...)的forEach不是一個函數 – Idlliofrio

+0

以及它的工作原理,但只顯示第一個文件名和電子郵件,而不是列出整個文檔。企業集合中 – Idlliofrio

+1

你的問題是'forEach'所以我出了這個問題。但是,如果你想返回*所有文檔名稱*然後*推入數組*並返回它。見更新答案:) @Idlliofrio –

1

forEach只適用於數組,並且您正在貓鼬模型上使用它。 試試這個:

Enterprise.find().exec(function(err, docs) { 
    docs.forEach(function(doc) { 
    // do something with all the documents 
    } 
    // do something outside the loop 
})