开发者

Embedded documents in forms with Mongoose

I have a simple Mongoose schema called Question that stores a question and its possible answers. Answers are a separate schema and are stored in Questions as embedded documents.

Here's the schema:

var ResponseSchema = new Schema({});

var AnswerSchema = new Schema({
    answer              : String
  , responses           : [ResponseSchema]
 });

 var QuestionSchema = new Schema({
    question            : {type: String, validate: [lengthValidator, "can't be blank."]}
  , answers             : [AnswerSchema]
});

I'm trying to create a form (I'm using express and jade) that allows a user to enter a question and some answers.

Here's what I have so far:

form(action='/questions', method='post')
fieldset
    p
        label Question
        input(type='text', name="question[question]")
div
    input(type='submit', value='Create Question')

And h开发者_JAVA百科ere's how I save it:

app.post('/questions', function(req, res, next) {
  var question = new Question(req.param('question'));
  question.save(function(err) {
    if (err) return next(err);

    req.flash('info', 'New question created.');
    res.redirect('/questions');
  });
});

This works great but leads me to my question... how would I add answers in this form?

(or a more general question, how would I put an embedded document in a form like this?)

I tried Googling around and looking at lots of examples and I didn't run into this, thanks for taking a look.


You can "push" answers into the answers array like this:

   question.answers.push( { answer: "an answer here" });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜