【问题标题】:How to access object with req.body in Mongoose?如何在 Mongoose 中使用 req.body 访问对象?
【发布时间】:2021-07-18 15:30:57
【问题描述】:

我想创建一个新调查,并希望用户根据调查类型(多选或真/假)输入自己的问题。我希望用户输入 QuestionText 但我的架构结构如下:

// create a question model
let questionModel = mongoose.Schema(
  {
    "MC": 
    {
        "QuestionText": String,
        "Options": [String]
    },
    "TF":
    {
        "QuestionText": String,
        "Options": Boolean
    }
  }
);


// create a survey model
let surveyModel = mongoose.Schema(
  {
    "Title": String,
    "Type": [String],
    "Questions": [questionModel],
    "Answered": { type: Number, default: 0 }, // how many times users answered
    "DateCreated": String,
    "Lifetime": Number // Survey expiry in seconds
  },
  {
    collection: "surveys",
  }
);

我不确定如何通过 req.body.Questions 访问“MC”对象中的 QuestionText 字符串。这就是我现在所拥有的。谁能帮帮我?

// POST route for processing Create Survey Page - CREATE
router.post("/create", (req, res, next) => {
  let newSurvey = Survey({
    Title: req.body.Title,
    Type: req.body.Type,
    Questions: req.body.Questions[0].MC.QuestionText,
  });

  Survey.create(newSurvey, (err, Survey) => {
    if (err) {
      console.log(err);
      res.end(err);
    } else {
      // refresh survey list
      res.redirect("/live-surveys");
    }
  });
});

"Title": "Some Survey",
    "Type": ["MC"],
    "Questions": [{
        "MC": {
            "QuestionText": "Favorite Color?",
            "Options": ["red", "blue", "green", "yellow"]
        }
    }],
    "Answered": {
        "$numberInt": "0"
    },
    "DateCreated": "Date",
    "Lifetime": {
        "$numberInt": "20"
    }

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    req.body需要解析成json

    
    const parsedBody = JSON.parse(req.body)
    parsedBody.Questions[0].MC.QuestionText // will now be accesible
    
    

    【讨论】:

    • 感谢您的回复,当我转换 JSON 时,它现在给我这个错误“无法将对象转换为原始值”
    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 2014-08-15
    • 1970-01-01
    • 2019-12-27
    • 2018-09-15
    • 2017-10-03
    • 2017-08-08
    • 2019-05-04
    相关资源
    最近更新 更多