我有一个名为 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/