我的课程架构如下所示
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
current_education: {
type: String,
required: true
},
course_name: {
type: mongoose.Schema.Types.ObjectId,
ref:'Course'
},
address: {
type: String,
required: true
},
mobile_number: {
type: Number,
required: true
},
date: {
type: Date,
default: Date.now
}
})
并且我正在尝试使关系学生成为该课程的学生。在控制器中,我正在尝试根据如下课程ID填充课程详细信息
exports.createStudent = async (req, res) => {
try {
const student = new Student(req.body);
const result = await student.save().then(t => Course.findById(req.body.course_name).populate('courses'));
if (!result) res.send('something went wrong');
res.send(result)
} catch (e) {
res.send(e);
}
}
在邮递员中我的发布方式,您可以在下面查看
{
"name":"Ram",
"current_education":"B.tech",
"course_name":"5cb804f1e97ba91cb8ca9dac",
"address":"Bangalore",
"mobile_number":7894561236
}
答案 0 :(得分:1)
我想您想要学生详细信息以及课程详细信息:
这是您实现的方式:
exports.createStudent = async (req, res) => {
try {
const student = new Student(req.body);
const result = await student.save().then(t =>
Student.findById(student._id).populate('course_name')); // Pass new ID and then populate the "course_name"
if (!result) res.send('something went wrong');
res.send(result)
} catch (e) {
res.send(e);
}
}
希望这可以解决您的查询!