1 回答

TA贡献1155条经验 获得超0个赞
在您的架构代码中,您需要定义字段类型,如 name: String 而不是 name: "String"。
您的架构必须是这样的:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new Schema(
{
name: String,
surname: String,
team: String,
project: String,
id: String
},
{ collection: "UserData" }
);
module.exports = mongoose.model("user", userSchema);
此外,您已经创建了用户模型,因此在 userRoute 中无需这样做:
const User = mongoose.model('user');
您只需要像这样在 userRoute 中正确导入 User 模型。
const User = require("../models/User"); // you can change the path if it is not correct
最后,要为 post 数据启用 json,您需要将此行添加到您的 index.js:
app.use(bodyParser.json());
通过这些更改,您可以使用这样的 json 主体使用此 URL http://localhost:3000/user创建一个用户:
{
"name": "John",
"surname": "Doe",
"team": "CE",
"project": "Project1",
"id": "2"
}
这将给出如下结果:
{
"error": false,
"user": {
"_id": "5dce7f8c07d72d4af89dec57",
"name": "John",
"surname": "Doe",
"team": "CE",
"project": "Project1",
"id": "2",
"__v": 0
}
}
此时,您将拥有一个 UserData 集合。
当您向http://localhost:5000 url发送 get 请求时,您将获得如下用户:
[
{
"_id": "5dce75a91cbb4e5f7c5ebfb3",
"name": "John",
"surname": "Doe",
"team": "CE",
"project": "Project1",
"id": "2",
"__v": 0
}
]
添加回答
举报