【发布时间】:2020-01-30 18:11:17
【问题描述】:
我正在使用 express/bodyparser/MongoDB/postman 制作 API,但是每当我发送 POST 请求时,Schema 都会返回错误,我该如何解决这个问题?
我在 Postman 中尝试了不同的选项,例如检查我是否有正确的选项并确保其设置为 JSON。
我的要求如何:
const express = require("express");
const app = express();
const todoRoutes = require("./routes/todos");
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
我的架构是什么样子的:
var todoSchema = new mongoose.Schema({
name: {
type: String,
required: "Use a string"
},
completed: {
type: Boolean,
default: false
},
created_date: {
type: Date,
default: Date.now
}
});
我的 POST 请求的外观:
router.post("/",function(req,res){
console.log(req.body);
db.Todo.create(req.body)
.then(function(newTodo){
res.json(newTodo);
})
.catch(function(err){
res.send(err);
});
});
邮递员返回的错误:
{
"errors": {
"name": {
"message": "Use a string",
"name": "ValidatorError",
"properties": {
"message": "Use a string",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "Todo validation failed",
"message": "Todo validation failed: name: Use a string",
"name": "ValidationError"
}
当我给出名称键和 GoT 值时,req.body 的 console.log :
'{\n "name" : "watch GoT"\n}': " }
我看到的主要奇怪的事情是,出于某种原因,我首先从 req.body 得到了一个奇怪的日志(不寻常的'和\n)
【问题讨论】:
-
您在 Postman 中的请求是什么样的?你要寄什么?
-
@DannyDainton 我正在为我的数据库发送一个测试条目,其键为“name”,值为“Got”。但它不被我所做的模式所接受,回馈“不是字符串”
-
你能用一张图片更新问题吗?
-
@DannyDainton 更新了它,请注意,我也使用 选项卡以相同的结果做了完全相同的事情
标签: mongodb express postman body-parser