0

So I've been trying to figure out what exactly I'm missing in a logic loop I've created. The following example closely recreates my situation:

async function x() {
    const items = await Items.find().exec();
    console.log(items);
    for(item in items) {
        console.log(item);
    }
}

So the outcome for that little code block for me is that items holds an array of mongoose documents as expected, but here is the issue: item apparently is 0.

When I look at the mongoose document the only value that is 0 on it is the __v value, which in my understanding is the version that document is at. Am I just missing something or is this just not possible?

To note this returns as expected:

async function x() {
    const items = await Items.find().exec();
    console.log(items);
    items.forEach(item => {
        console.log(item);
    });
}

This logs both the array and a single mongoose document, the issue is I'm looking to do another async call in that second loop that I want to await so if that's not possible I'll have to break it up more I guess, but I'd like ot know where that 0 is coming from if possible.

EDIT: To clarify, I have tried running toObject on both but it doesn't seem to change anything, and actually on the array it says toObject isn't a function of the array.

EDIT 2: I was not asking why for...in was bad, I was asking why it was not iterating over the "array" I had, it was due to the fact that mongoose returns a collection and for...in iterates over the enumerable properties of an object.

firrae
  • 171
  • 1
  • 13

1 Answers1

1

iterating over an array using

for(item in ['a', 'b']) {
  console.log(item)
}

will give you the array indexes: 0, 1

You are looking for

for(const item of ['a', 'b']) {
  console.log(item)
}

And that will print values: a, b

Check this

ztrange
  • 305
  • 2
  • 9
  • Thanks, I didn't realize the different between for...of and for...in, I thought they acted the same. – firrae Dec 22 '16 at 14:14