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.