0

I am creating a questionnaire that has the following schema:

var questionnaireSchema = new Schema({
    user_id : String,
    start_date : Date,
    end_date : Date,
    questions : [{
        question_id : {type: Number},
        answer_id : {type: Number},
        answer_string : String
    }]
});

I need to be and to find an answer set by the user_id and then see if that user has answered that question already.

I have the following query:

Questionnaire.findOne({'user_id': req.body.uid}, function (err, user) {
        if (err) {
            throw err;
        }
        if (user) {

            Questionnaire.findOne({
                'uid': req.body.uid,
                'questions.question_id': req.body.question_id

            }, function (err, question) {
                if (question) {
                    console.log('Found a question - updating');
                } else {
                    console.log('No question found - adding');
                }
            });
        }
    });

The query finds the user, however, when I try to find the user and question.answer_id together, the query never find anything.

I'm not sure how to write this query or where to look.

Thank you

4
  • 2
    What's that Assesment model? Shouldn't the query be on Questionnaire too, and reduced the code to a single query? Commented Oct 14, 2016 at 14:38
  • Sorry, i've updated it. It needs to have both queries. Its the second query that I'm having trouble with? Commented Oct 14, 2016 at 14:46
  • 1
    Where is uid key in the Questionnaire model? Commented Oct 14, 2016 at 15:11
  • @chridam That was exactly my problem. Thank you Commented Oct 14, 2016 at 15:36

1 Answer 1

1

question_id is a Number in your schema. What's the type of req.body.question_id?
Depending on the request's content-type, it could be a string, hence the 2nd query cannot match anything.

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.