简体   繁体   English

如何在 Mongoose 中使用 req.body 访问对象?

[英]How to access object with req.body in Mongoose?

I would like to create a new survey and would like the user to enter their own question based on type of survey(Multiple Choice or True/False).我想创建一个新调查,并希望用户根据调查类型(多选或真/假)输入他们自己的问题。 I would like the user to enter the QuestionText but my schema is structured like this:我希望用户输入 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", } );

I am unsure of how to access the QuestionText string in the "MC" object through req.body.Questions.我不确定如何通过 req.body.Questions 访问“MC”对象中的 QuestionText 字符串。 This is what I have right now.这就是我现在所拥有的。 Can anyone help me out?谁能帮我吗?

 // 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" }

req.body needs to be parsed into json req.body需要解析成json


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

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

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