node.js - 使用 Mongoose 将文档嵌入表单中

标签 node.js express mongoose pug

我有一个名为 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和jade),允许用户输入问题和一些答案。

这是我到目前为止所拥有的:

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

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

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

我尝试在谷歌上搜索并查看很多示例,但没有遇到这个问题,感谢您的浏览。

最佳答案

您可以将答案“推送”到答案数组中,如下所示:

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

关于node.js - 使用 Mongoose 将文档嵌入表单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944292/

相关文章:

node.js - Module.export 一个 'default' 函数

javascript - Sails : JSON array of Model objects successfully created and displayed, 但只有一些保存到数据库

node.js - 如何将nodejs和express设置为 digital ocean 上的docker容器?

javascript - Object.assign 没有按预期工作

node.js - Passport 本地 Mongoose 错误: No Username Was Given

javascript - Socket.io 与 require.js 异步且 io 未定义

javascript - 在回调中重用变量/对象

javascript - 如何在 express.js 中抛出 404 错误?

javascript - 类型错误 : User is not a constructor

javascript - Mongo 返回未定义但数据存在