node.jsnpm-shrinkwrap

Foreach undefined for data that comes from query


My query works fine, if I do not use shrinkwrap or yarn on my aws ubuntu 14.04 machine.

However, the same query works fine with shrinkwrap/yarn on local machine, but somehow they don't work on aws machine.

The query is as shown below:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var foodtr = require('./../model/foodtruck');

var foodtrucklist = function(req, res) {
    foodtr.find().populate('item_list').exec(function(err, foodtrucks) {
        foodtrucks.forEach(function(ftr) {
            var start_time = ftr.foodtruck_starting_timing;
            var end_time = ftr.foodtruck_closing_timing;
            var foodtruck_open_status = ftr.foodtruck_open_status;
            // var shut_down = ftr.foodtruck_shutdown;
            if ((start_time && end_time) &&
                (start_time.trim() != '' &&
                    end_time.trim() != '')) {
                if (inTime(start_time, end_time) &&
                    foodtruck_open_status ==0 ) {
                    ftr.foodtruck_open_status = 0;
                    ftr.save();
                } else {
                    ftr.foodtruck_open_status = 1;
                    ftr.save();
                }
            }
        })

        res.json({
            status: '200',
            message: 'foodtrucklist',
            data: foodtrucks
        });
    });
};

The error that I am getting is :

events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'forEach' of undefined
    at /home/bitnami/quflipNodeAPI/controller/foodtrucklist.js:9:19
    at /home/bitnami/quflipNodeAPI/node_modules/mongoose/lib/query.js:2745:9
    at newTickHandler (/home/bitnami/quflipNodeAPI/node_modules/mpromise/lib/promise.js:234:18)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

Solution

  • You need to handle errors:

    foodtr.find().populate('item_list').exec(function(err, foodtrucks) {
        // INSERT ERROR HANDLING HERE
        foodtrucks.forEach(function(ftr) {
    

    For example:

    foodtr.find().populate('item_list').exec(function(err, foodtrucks) {
        if (err) {
            console.log('ERROR:', err);
            return res.status(500).json({ error: err });
        }
        foodtrucks.forEach(function(ftr) {
    

    You should access foodtrucks only when err is not defined - because it's only one that is defined - either err or foodtrucks. When you don't check for errors, you will sometimes access data that is not defined and you will get errors like this.