2

In my app.js, I have the following:

post.find({'global': true}).sort('date').exec(function(err, data) {
  for (var i = 0; i <= data.length; i++) {
    console.log(data[i].email);
    //socket.emit('Post', {name: data[i].name, cont: data[i].cont, date: data[i].date});
  }
});

When I use

console.log(data[i]);

I get my data in the form of

{name: blah, cont: blah, email: blah, etc}

But when i try emitting the data

data[i].attribute

I get the error

TypeError: Cannot read property 'attribute' of undefined

I know the data is there, as I am able to log it in the console. Why can't I access the specific attribute of the array? Any ideas?

1 Answer 1

1

It might be because of how you're using your loop. Your logic with <= will causes the loop to run one extra time, therefore accessing an array value that doesn't exist. This is a case of what's happening:

var data = [{ foo: 'bar1' }, { foo: 'bar2' }];
for (var i = 0; i <= data.length; i++) {
  console.log(data[i].foo);
}

The loop will run three times instead of twice, causing this to happen:

console.log(data[0].foo); // bar1
console.log(data[1].foo); // bar2
console.log(data[2].foo); // TypeError: Cannot read property 'foo' of undefined

To fix this, change your loop to for (var i = 0; i < data.length; i++).

Also, a debugging tip: you should try using output when inspecting errors like yours, even if data was an array with a length of a thousand, the error would still only be thrown on the last iteration, and with socket.emit() it would appear as if the loop only ran once.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.