【问题标题】:How to access object with req.body?如何使用 req.body 访问对象?
【发布时间】:2021-07-18 12:47:10
【问题描述】:

我想创建一个新调查,并希望用户根据调查类型(多选或真/假)输入自己的问题。我希望用户输入 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"
    }

【问题讨论】:

  • 可以添加 JSON 有效负载吗?
  • @sid 当然,我已经添加了
  • 那么这里的问题是什么?如果您将有效负载作为对象而不是数组接收并且问题数组的第一个索引为 MC,则您的代码 req.body.Questions[0].MC.QuestionText 是正确的。您能否详细说明具有挑战性的部分

标签: javascript node.js express mongoose


【解决方案1】:

获取req.body 的结果并使用JSON.parse 将其解析为json,将返回的内容分配给某个变量。

该变量现在将是一个对象,允许您访问其中的道具。

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2021-07-25
    • 2021-07-02
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2020-09-13
    相关资源
    最近更新 更多