//服务器.js
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config({ path: "./config.env" });
const app = require("./app");
mongoose
.connect(process.env.LOCAL_CONN_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((conn) => {
console.log(`Connection successfull with : ${conn}`);
})
.catch((err) => {
console.log("error is: ", err);
});
// **************************************
// start the server
app.listen(5000, () => {
console.log("server has started");
});
// 控制器 `
createCategory = async(req, res) => {
try {
const { name } = req.body;
const category = await Category.create(
{ name },
{
new: true,
runValidators: true,
}
);
res.status(200).json({
status: "success",
data: {
category,
},
});
} catch (err) {
res.status(404).json({
status: "fail",
data: {
error: err.message,
},
});
}
};
// 验证器是 `
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: [true, "category must be specified"],
minlength: 10,
maxlength: 100,
unique: [true, "Category name must be unique"],
},
});
我期待该文档将被创建,并且它已创建,如您在 mongoDb 指南针中的图像中看到的那样,但我的 catch 块仍然执行,这里出了什么问题帮助?
您需要添加此行才能解析请求正文。
app.use(express.json());