0

I'm new to mongodb. I'm doing this student project which is a web app that generates multiple choices. After user submits answer, app checks user's answers against the correct ones to provide feed back.

I have the question bank with correct answer stored in one collection. After a user submits his answer, an array contains _id with user's choice gets sent to the nodejs backend.

To check user's answers, my approach now would be something like:

app.post('/submitquiz', function (req, res) {
    var  arr = [], answer;
    for (answer in req.body){
        var correctChoice = questionModel.find({_id:answer._id}).correctChoice;
        if (correctChoice != answer.choice){
            arr.push({
                '_id':answer._id,
                'correctChoice': correctChoice
            })
        }
    }
    res.send(arr);
});

Wanna know if there's an elegant way to do this in mongodb, is there anything built in I can utilize to achieve this?

Thanks!

pcs
  • 1,864
  • 4
  • 25
  • 49
  • questionModel.find is async task. and for iterating loop, you have used for loop. So it might be happened that most of the time you will get empty array in response. – Hiren S. Aug 08 '15 at 07:27
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Blakes Seven Aug 08 '15 at 07:46
  • @BlakesSeven While we are talking of an asynchronous call here, the main question is about how to implement a multiple choice check in MongoDB. – Markus W Mahlberg Aug 08 '15 at 08:01
  • depending on the number of answers it may be better to get all the correct answers loaded, like: `db.questionModels.find({_id: { $in: [question_id1, question_id2, .... ] }})` and then find matches in memory (you could event try to cache them, if they aren't changing). The other thing is dealing with asynchronicity. – szymek Aug 08 '15 at 11:42

0 Answers0