0

I'm a little lost with how I need to structure this POST route to save two related mongoose models. I'm also relatively new to node and callback functions.

Below are my mongoose schemas.

question.js:

...
var questionSchema = new Schema({
    text: String,
    choices: {
        type: Schema.ObjectId,
        ref: 'choices'
    }
});

module.exports = mongoose.model('question', questionSchema);

choice.js:

...
var choiceSchema = new Schema({
    text: String,
    votes: Number
});

module.exports = mongoose.model('choice', choiceSchema);

Below is the route.

routes/index.js:

var express = require('express');
var Question = require('../models/question');
var Choice = require('../models/choice');
var router = express.Router();

...

router.post('/add', function(req, res, next){
    var body = req.body;
    var question = new Question({text: body.text});
    question.save(function(err) {
        if (err) {
            return handleError(err);
        } 
    });
    for (i=0; i<req.length; i++) {
        var chid = "choice".concat(String(i+1));
        var choice = new Choice({text: body[chid], votes : 0});
        choice.save(function(err) {
            if (err) return handleError(err);
        });
        console.log(choice);
        question.choices.push(choice);
        question.save(function(err) {
            if (err) return handleError(err);
        });
    }

Request bodies come in like this. The number of choices is variable:

{ text: 'question text', choice1: 'choice text', choice2: 'another choice text' }

This method saves the question but doesn't save any of the choices, nor does it even go into the for loop. I'm assuming that I need to place the for loop into a callback function, but I can't seem to figure out where. Advice, or an example of the desired functionality would be greatly appreciated.

Marcus Dash
  • 55
  • 1
  • 5
  • See how all of these calls have a "callback" method that you have used? That is because that code is only called once the I/O operation associated has completed. Which means that the following lines after these calls and "not" inside the callback block do not wait for or completion of the preceding lines and nor is their variable content available. Continuation logic needs to occur "inside" the callback. – Blakes Seven Sep 17 '15 at 01:43
  • 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 Sep 17 '15 at 02:19

0 Answers0