As I understand, you want to embed courses into the user model.
(据我了解,您希望将课程嵌入用户模型。)
So you need to make this change in your user model:
(因此,您需要在用户模型中进行以下更改:)
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let userSchema = new Schema({
email: { type: String, required: true },
password: { type: String, required: true },
name: { type: String, required: true },
phoneNumber: { type: Number, required: true },
schedule: { type: String, required: true },
courses: [
new Schema({
name: String
})
]
});
module.exports = mongoose.model("User", userSchema);
And create a course for the given user like this:
(并为给定的用户创建一个课程,如下所示:)
app.post("/user/:id/course", async (req, res) => {
const result = await User.findByIdAndUpdate(
req.params.id,
{
$push: {
courses: {
name: req.body.name
}
}
},
{
new: true
}
);
res.send(result);
});
When you send a request to url http://localhost:3000/user/5de2cf9323f76c207c233729/course
with this body: (Note that 5de2cf9323f76c207c233729 is an existing user _id)
(当您使用此正文向URL http://localhost:3000/user/5de2cf9323f76c207c233729/course
发送请求时(请注意5de2cf9323f76c207c233729是现有用户_id))
{
"name": "Course 1"
}
The response will be like this, meaning the course is added to the user:
(响应将如下所示,这意味着该课程已添加到用户:)
{
"_id": "5de2cf9323f76c207c233729",
"email": "[email protected]",
"password": "123123",
"name": "Max",
"phoneNumber": 123123123,
"schedule": "sc1",
"courses": [
{
"_id": "5de2cfa723f76c207c23372a",
"name": "Course 1"
}
],
"__v": 0
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…