节点表示mongoose集合不保存

时间:2015-09-17 01:15:41

标签: javascript node.js mongodb express mongoose

我有点迷失了我需要构建这个POST路由以保存两个相关的mongoose模型。我对节点和回调函数也比较陌生。

以下是我的mongoose架构。

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);

以下是路线。

路由/ 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);
        });
    }

请求机构就像这样进来。选择的数量是可变的:

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

此方法保存question,但不保存任何choices,也不会进入for循环。我假设我需要将for循环放入回调函数,但我似乎无法弄清楚在哪里。建议或所需功能的一个例子将不胜感激。

0 个答案:

没有答案