使用 Mongoose 将文档嵌入表单中

发布于 2024-11-27 23:05:54 字数 1175 浏览 1 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜巴黎 2024-12-04 23:05:54

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

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

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

   question.answers.push( { answer: "an answer here" });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文