【问题标题】:I get this error "Cast to String failed for value \"{}\" at path \"body\"" When saving post data to my mongodb collection, Nodejs我收到此错误“Cast to String failed for value \"{}\" at path \"body\"" 将帖子数据保存到我的 mongodb 集合时,Nodejs
【发布时间】:2019-09-03 11:12:46
【问题描述】:

我无法将任何内容保存到我的新 mongodb 集合中,因为我不断收到此错误

    "message": "Cast to String failed for value \"{}\" at path \"body\""

过去我已经成功地使用模型将数据添加到我的 mongodb 集合中,没有任何问题,但我今天尝试创建一个新模型,当我决定使用邮递员对其进行测试时,我一直收到此错误。我尝试在线阅读但找不到答案,请帮助。

这是我的架构

const mongoose = require("mongoose");

const ticketSchema = new mongoose.Schema({
  sender: {
    type: String
  },
  body: {
    type: String,
    required: true
  },
  ticketStyle: {
    type: String
  },
  ticketStatus: {
    type: String
  },
  response: {
    type: String,
    required: false
  }
});

const Ticket = mongoose.model("Ticket", ticketSchema);

module.exports = Ticket;

这是路线

router.post("/support", (req, res) => {
  const body = req.body;
  const sender = "admin";
  const ticketStyle = "userstyle";
  const ticketStatus = "pending";
  const newTicket = new Ticket({
    body,
    sender,
    ticketStyle,
    ticketStatus
  });
  newTicket
    .save()
    .then()
    .catch(error => {
      res.send(error);
    });
});

我想将这些帖子添加到我的收藏中,但由于需要“body”密钥对并且我不断收到此错误,所以我被卡住了

【问题讨论】:

标签: node.js mongodb express model postman


【解决方案1】:

刚刚发现问题(笨拙的错误),这是由于我决定如何命名变量引起的问题。我更新了架构和变量名称,一切都按预期工作。

新路线:

router.post("/", (req, res) => {
  const sender = "admin";
  const message = req.body.message;
  const ticketStatus = "pending";
  const ticketStyle = "userTicket";
  const newTicket = new Ticket({
    sender,
    message,
    ticketStyle,
    ticketStatus
  });
  newTicket
    .save()
    .then(tickets => {
      res.redirect(req.originalUrl);
      console.log("Successfully saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
      console.log("unable to save to database");
    });
});

我也更新了模式名称。

const ticketSchema = new mongoose.Schema({
  sender: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  },
  ticketStatus: {
    type: String
  },
  ticketStyle: {
    type: String
  },
  reply: {
    type: String
  }
});

问题在于请求路由中的正文数据只是 req.body,而不是 req.body.message,所以我猜代码试图将整个 JSON 文件保存/使用为字符串(我猜)。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2017-08-14
    • 2017-03-23
    • 2017-02-06
    • 2013-02-03
    • 2022-06-14
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多