简体   繁体   中英

Mongoose: How to query field in document

I have a document that has array of questions, I want each time I submit button the function is run that request next question in the array of question, basically its quiz app where I want to show questions from database that is saved in the document and all questions are saved in the array

Is it right the way I structured data ie all question in an array and in single document

My question is how can I retrieve each question in the array that is saved in single document, I did something like this:

var schema = new mongoose.Schema({
question : []
})
var quizz = mongoose.model('Quiz', schema );

var firstDoc = new quizz({
question: ['question 1', 'question 2', 'question 3', 'question 4']
})

firstDoc.save(function(err, res){
 if(err){
   console.log("error occured while saving document object " + err )
 }else{
   console.log("saved data");
 }
})

should I have to make some ID to identify each question in array so that I can pull question based on ID or this is right what I'm doing

To look at documents with specific value in the array you have to use $in :

quizz.findOne({ question: {$in: ['question 1'] }, function (err, doc) {
   console.log(doc);
});

A correct schema for your purpose should be like this:

var QuestionSchema = new mongoose.Schema({
   question: String
});

Then you can use the schema to create a document for each question you have.

var firstQuestion = new quizz({
   question: 'question 1'
});
var secondQuestion = new quizz({
   question: 'question 2'
});

etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM