使用 Mongoose 将文档嵌入表单中
我有一个名为 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');
});
});
这很好用,但让我想到了我的问题...... 我如何以这种形式添加答案?
(或者一个更一般的问题,我如何将嵌入式文档放入这样的形式中?)
我尝试用谷歌搜索并查看很多示例,但我没有没有遇到这个,谢谢您的浏览。
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 here'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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将答案“推入”答案数组,如下所示:
You can "push" answers into the answers array like this: