简体   繁体   English

如何在嵌套猫鼬模式中将输入数组保存到子模式?

[英]How to save array of inputs to a child schema in a nested mongoose schema?

I am trying to save a survey which contains multiples questions. 我正在尝试保存一个包含多个问题的调查。 Each time I enter a question and the answers and click the save button it should push it to the question array and at last when I click the save survey button the whole question should be saved under the parent schema 'survey'. 每次我输入问题和答案并单击保存按钮时,它都应将其推送到问题数组,最后,当我单击保存调查按钮时,整个问题应保存在父模式“调查”下。

How can I do this with nodejs and mongoose? 我该如何使用nodejs和mongoose? What I tried is here.... 我尝试过的是这里...

Mongoose schema 猫鼬模式

 var mongoose = require("mongoose");
 var Schema = mongoose.Schema;

 var SurveySchema = new Schema({
    surveyname: String,
    question  : [{
        que: String,
        ans1: String,
        ans2: String,
        ans3: String,
        ans4: String

        }]
    });

 module.exports=mongoose.model('Survey',SurveySchema);

The js file where I save the inputs to the schema 我将输入保存到架构的js文件

var express = require('express');
var router = express.Router();
var survey = require('../models/QBank');

router.post('/', function(req, res, next){ 
  new survey({
    surveyname: req.body.sname,
    for(var i=0;i<5;i++){
      question.question.push({
        que: req.body.que,
        ans1: req.body.ans1,
        ans2: req.body.ans2,
        ans3: req.body.ans3,
        ans4: req.body.ans4
      });
    }

    }).save(function(err, doc){
      if(err) res.json(err);
      else
          req.flash('success_msg', 'Question saved to QBank');  
      res.redirect("/CreateSurvey");

    });

});

module.exports = router;

I am stuck here with my project. 我在这里停留我的项目。

You can use an atomic update method like findOneAndUpdate() for your post where you can specify the upsert option. 您可以在帖子中使用诸如findOneAndUpdate()类的原子更新方法,在其中可以指定upsert选项。 If upsert is true and no document matches the query criteria, findOneAndUpdate() inserts a single document. 如果upsert为true,并且没有文档符合查询条件,则findOneAndUpdate()将插入一个文档。 Here that's where you can also use the native $push operator to push the new question and answers to the question array, rather than using a loop when you can let mongo do all the work on the server. 在这里,您还可以使用本地$push运算符将新问题和答案推送到问题数组,而不是在可以让mongo完成服务器上的所有工作时使用循环。

The following example shows how you can refactor your code: 以下示例显示了如何重构代码:

var express = require('express');
var router = express.Router();
var Survey = require('../models/QBank');

router.post('/', function(req, res, next){ 
    Survey.findOneAndUpdate(
        { "surveyname": req.body.sname }, /* <query> */
        { /* <update> */
            "$push": {
                "question": {
                    "que": req.body.que,
                    "ans1": req.body.ans1,
                    "ans2": req.body.ans2,
                    "ans3": req.body.ans3,
                    "ans4": req.body.ans4
                }
            } 
        },
        { "upsert": true }, /* <options> */
        function(err, doc){ /* <callback> */
            if(err) res.json(err);
            else
                req.flash('success_msg', 'Question saved to QBank');  
            res.redirect("/CreateSurvey");
        }
    );
});

module.exports = router;

In the above, the fields and values of both the <query> and <update> parameters are created if the <update> parameter contains update operator expressions. 在上面,如果<update>参数包含更新运算符表达式,则会创建<query><update>参数的字段和值。 The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter. 此更新根据<query>参数中的equals子句创建基础文档,然后根据<update>参数应用更新表达式。

First of all you need to populate your survey object when you enter question and answer and hit save button.Then you can use ajax form submit to send the data to the desired route. 首先,当您输入问题和答案并点击保存按钮时,您需要填充调查对象。然后您可以使用ajax表单提交将数据发送到所需的路线。

Let's say the survey object is like the following 假设调查对象如下

var randomSurvey = {
   surveyname: "randomSurvey",
   questions:[
             {     
                que: "question1",
                ans1: "answer1"
                ans2: "answer2"
                ans3: "answer3"
                ans4: "answer4"
              },
              {     
                que: "question1",
                ans1: "answer1"
                ans2: "answer2"
                ans3: "answer3"
                ans4: "answer4"
              }
            ]
}

And when you press the save survey button then your post route should be like this. 而且,当您按“保存调查”按钮时,您的发布路线应如下所示。

router.post('/', function(req, res, next){ 

  //Grab your data here sent over ajax form submit 
  var randomSurvey = req.body.randomSurvey;

  var newSurvay = new survey(randomSurvey);

  newSurvay.save(function(err, doc){
      if(err) {
         //do something with err
      }
      else{
        // do something with the result;
      }             
      res.redirect("/your_redirect_url");    
  });
});
var survey = require('../models/QBank');
var Survey = new survey();
var question = [];
question[0] =  req.body.que;
question[1] =req.body.ans1;

// do for all
Survey.question = question;
survey.save(Survey, function(err, doc){})

According to your description you may passed full question to save in DB. 根据您的描述,您可以传递完整的问题以保存在DB中。

Assumed you passed data in req.body with multiple question. 假设您在带有多个问题的req.body传递了数据。 like: 喜欢:

{surveyname: 'your survay name', question: [{que:'q1',ans1:'a1',....},{que:'q2'..},{que:'q3',..}]}

If assumption is correct then can use like: 如果假设正确,则可以使用:

router.post('/path', function(req, res, next){ 
  var newSurvay = new survey({
    surveyname: req.body.surveyname,
    question: req.body.question
    });

  newSurvay.save(function(err, doc){
      if(err) res.json(err);
      else
          req.flash('success_msg', 'Question saved to QBank');  
      res.redirect("/CreateSurvey");

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM