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)
{
"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
}