1

I'm new on MongoDB and I wanted to store an array.

Here's an example of what I want

question : {
    question : "My question",
    answer   : "My answer",
    subQuestions : 
    [0] {
        question: "My sub question",
        answer  : "My sub answer"
    },
    [1] {
        question: "My other sub question", 
        answer  : "My other sub answer"
    }
}

But I didn't succeed to put multiple entries in subQuestions. I got this instead :

question : {
    question : "My question",
    answer   : "My answer",
    subQuestions : {
        question {
            [0] : "My sub question",
            [1] : "My other sub question"
        },
        answer {
            [0] : "My sub answer",
            [1] : "My other sub answer"
        }
    }
}

What I have actually is hard to process in front and I really wanted to have what I've showed in the first bloc.

This is my actual Schema :

var Questions = new Schema({
    question: { type: String },
    answer  : { type: String },
    subQuestions : {
        question : [String],
        answer   : [String]
    }
});

And my saving script :

var q = new Questions;
q.subQuestions.question = ["My sub question", "My other sub question"];
q.subQuestions.answer   = ["My sub answer", "My other sub answer"];

q.save(function(err){
    console.log(err);
});

Can someone help me with this ? I'm on it from awhile so maybe it's just a little thing that I didn't think about.

Thank you very much in advance and don't hesitate to ask me questions.

2
  • How does your mongoose schema look like? Commented Apr 10, 2015 at 22:01
  • Thanks for helping. My actual mongoose Schema look like the third block code on my question. Commented Apr 10, 2015 at 22:11

1 Answer 1

3

You just have to define an array in your schema:

var Questions = new Schema({
    question: { type: String },
    answer  : { type: String },
    subQuestions : [{
        question : String,
        answer   : String
    }]
});

Note that I changed your curly braces.

To add a new subquestion you can use push():

q = new Questions
sq.question = "How are you doing?"
sq.answer = "Great."
q.subQuestions.push(sq)

I didn't test this code but it first assembles a JavaScript object from two strings (this is the sq object) and then pushes it to the array.

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.