简体   繁体   中英

NodeJS - Events.js cannot read property forEach of undefined

I'm facing an issue since 2 days and i can't figure out how to fix it. I've an error on forEach, so my application runs well and then stops without any explication.

Here is the code where the error happens.

    var easy = setInterval(function(){
        keywords.forEach(function(k) {
            tweetModel.find({keyword: k}).sort({date: -1}).limit(20).exec(function(err, data) {
                var score = [];
                var date = [];
                console.log(data);
                console.log(err)
                data.forEach(function (item) {
                    score.push(Math.floor(parseFloat(item.score) * 1000) / 1000);
                    date.push(item.date.getDate()+'/'+parseInt(item.date.getMonth() + 1)+'/'+item.date.getFullYear()+':'+parseInt(item.date.getHours() + 1)+':'+item.date.getMinutes());

                    tArrayStats[k] = score;
                    tArrayStats['date'] = date;
                });

            });

        });

        io.sockets.emit('stats',tArrayStats);
    },3000);

The error is thrown here

data.forEach(function (item) 

but i can't figure out why ! Thanks for you help.

As asked there is the output of console log data :

在此处输入图片说明

EDITED working code, thanks to @Ids van der Zee

var easy = setInterval(function(){
    keywords.forEach(function(k) {

        tweetModel.find({keyword: k}).sort({date: -1}).limit(20).exec(function(err, data) {
            if (data && !err)
            {
                var score = [];
                var date = [];
                console.log(data);
                console.log(err)

                data.forEach(function (item) {
                    score.push(Math.floor(parseFloat(item.score) * 1000) / 1000);
                    date.push(item.date.getDate()+'/'+parseInt(item.date.getMonth() + 1)+'/'+item.date.getFullYear()+':'+parseInt(item.date.getHours() + 1)+':'+item.date.getMinutes());

                    tArrayStats[k] = score;
                    tArrayStats['date'] = date;
                });
            }

        });
    });

    io.sockets.emit('stats',tArrayStats);
},3000);

on the line:

tweetModel.find({keyword: k}).sort({date: -1}).limit(20).exec(function(err, data) {

you are trying to find data corresponding to the keyword k, you are doing this for each keyword. If tweetModel does not contain the keyword you are looking for the data variable will be undefined. You can resolve this by checking if data is not undefined. Instead of

data.forEach(function (item){...

    if(data){
       data.forEach(function (item){...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM