user2573690 user2573690 - 3 years ago 82
Javascript Question

Loop through all elements of array inside array?

I'm completely drawing a blank as to what I am doing wrong here. I am trying to query an array inside my mongoose model and I just can't seem to get it. I'm sure its something simple.

My model looks like this:

var aSchema= new mongoose.Schema({
userType: String,
arr: [
{
id: Number,
name: String,
description: String,
attribute: String,
answerType: String,
textAnswer: String,
skill: [
{
heading: String,
detail: String
}
]
}
]
});


I want to loop through all questions and print out the name for each record. I tried the following:

a.find({ "userType": "test" }, { "arr": 1 }, function(err, users) {
if (err) {
console.log(err);
} else {
for (i = 0; i < users.length; i++) {
console.log(users[i].name);
}
}
});


I keep getting undefined for the name, how can I access the name of each element in my users array?

Thank!

Answer Source
a.find({ "userType": "test" }, { "arr": 1 }, function(err, users) {
        if (err) {
            console.log(err);
        } else {
            for (i = 0; i < users.length; i++) {
                console.log(users[i].arr[0].name);
            }
        }
    });

should work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download