使用Mongoose查询是正确的,但是forEach之后数组总是空的.Nodejs / MongoDB

Correct query using Mongoose, but array is always empty after forEach. Nodejs/MongoDB

本文关键字:数组 Nodejs MongoDB 之后 但是 查询 Mongoose 使用 forEach      更新时间:2023-09-26

我想在异步方法中的forEach之后返回一个名称数组。for each和res.send都在asynn中。方法。forEach工作得很好,但我总是得到一个空数组。

这是我在网站方面的请求:

function retrieveCharity(){
    $.ajax({
        type:"GET",
        url: "http://xxx.xxx.x.xx:9000/charity",
        success: function(data){
             data.charities.forEach(function(charityName){
                 $(".charity-ul").append("<li>"+charityName+"</li>");
             })
        }
    })
}
这是我的路由器。在NodeJs端获取监听器:
router.get('/', function (req, res){
   log.d("Entrou no method post - Charity"); 
   teamModel.find({},function(err,charities){
    var charityMap = {};
        if(err){
            console.log("Err in retrieving Charity")
            log.d("Err in retrieving")
            res.send({
                "status":"error"
            })
        }else{
            charities.forEach(function(charity){
                    charityMap[charity._id]= charity.teamName;
            console.log("Print here the name of the charities I have,PLEASE" + charity.teamName);
                    log.d("foEach - data",charity);
            })
        res.send({
              "charities": charityMap
        })
        }
   })//end of findCahrity
});

所有的日志。d和我要求打印在里面的信息是正确的,并且打印出来了。问题是我返回的数组总是空的,但是(forEach)和res.send都在异步方法中。

我总是在邮局收到这个:

{
charities: { }
} 

控制台总是说:

Uncaught TypeError: undefined is not a function 

this line:

 data.charities.forEach(function(charityName){
有人能帮帮我吗?我做错了什么?

提前感谢。

我不认为Object.prototype.forEach是标准的。data.charities是一个对象而不是数组。你可以尝试从

更改路由器代码
var charityMap = {};

charityMap[charity._id]= charity.teamName;

var charityMap = [];

with charityMap.push(charity.teamName)

或更改客户端的迭代