Reputation: 1499
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.
Upvotes: 1
Views: 4015
Reputation: 1002
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.
Upvotes: 3