我无法将任何内容保存到我的新 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"密钥对并且我不断收到此错误,因此我被困住了
刚刚发现了这个问题(笨拙的错误(,这是由于我决定如何命名变量而导致的问题。我更新了架构和变量名称,并且都按预期工作。
新路线:
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 文件保存/使用为字符串(我猜(。