【问题标题】:Embedded documents in forms with Mongoose使用 Mongoose 在表单中嵌入文档
【发布时间】:2011-10-20 03:11:37
【问题描述】:

我有一个名为 Question 的简单 Mongoose 模式,它存储一个问题及其可能的答案。答案是一个单独的架构,并作为嵌入文档存储在问题中。

这是架构:

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

我正在尝试创建一个允许用户输入问题和一些答案的表单(我使用的是 express 和 jam)。

这是我目前所拥有的:

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

我是这样保存的:

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

这很好用,但让我想到了我的问题...... 如何在此表单中添加答案?

(或更一般的问题,我如何将嵌入的文档放入这样的表单中?)

我尝试用谷歌搜索并查看了很多示例,但我没有遇到这种情况,感谢您查看。

【问题讨论】:

    标签: node.js express mongoose pug


    【解决方案1】:

    您可以像这样将答案“推送”到答案数组中:

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

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 2016-05-31
      • 2012-06-23
      • 2018-11-09
      • 2012-04-14
      • 2013-03-07
      • 2015-07-17
      • 2012-02-18
      • 2012-08-26
      相关资源
      最近更新 更多