1

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!

0

1 Answer 1

1
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

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

2 Comments

Thanks, your answer pushed me in the right direction but I still needed to add the element number on the arr. 'users[i].arr[0].name. If you update your answer, I can mark it as the answer.
here you go ^_^

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.