node.js - 使用nodejs在猫鼬中加入两个集合
问题描述
我想加入两个集合MongoDB
。我有两个收藏 1. 学生 2. 课程。
学生收藏:
课程合集
我尝试了一些代码,但这不起作用。
这是我的代码
学生.js
router.get('/student/:id', function(req, res){
Student.find({_id:req.params.id}, function(err, user){
res.send(user);
})
})
这是架构:
学生.js
const mongoose = require('mongoose');
let StudentSchema = mongoose.Schema({
name:{
type: String
},
email:{
type: String
},
phone:{
type: String
},
password:{
type: String
},
course :[{
type: mongoose.Schema.Types.ObjectId,
ref: 'Course'
}]
}, { collection: 'student' });
const Student = module.exports = mongoose.model('Student', StudentSchema);
course.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let CourseSchema = mongoose.Schema({
student_id:{
type: String
},
course_name:{
type: String
},
course_cost:{
type: String
}
}, { collection: 'course' });
const Course = module.exports = mongoose.model('Course', CourseSchema);
解决方案
你需要这样查询:
findOne:查找单个文档(返回对象 {} )
find:查找多个文档(返回数组[])
Student.findOne({_id:req.params.id}, function(err, student){
if(!err && student){
Courses.find({student_id:req.params.id},function(error,courses){
if(!error && courses){
student.courses=courses;
}else{
student.courses=[];
}
res.send(student);
});
}
});
目前您正在获取 course :[]
,因为在学生收藏中没有找到字段,如您在照片 1 中看到的那样
您需要course :["coures_id1","coures_id2"]
在学生集合中插入文档时进行设置。
然后您可以使用mongoose populate将课程填充到学生中
Student.findOne({_id:req.params.id}).populate('course').exec(function(err,student){
res.send(student);
});
因此,当您从学生收藏中获取时,无需存储student_id
课程收藏中的字段。
推荐阅读
- python - 当第一个数字出现时如何在 Pandas 中拆分一列
- python - Python TCP劫持攻击在Linux上创建目录
- c++ - 将读取值从 txt 复制到向量
- r - 如何在 Sweave 中使输出可识别
- sql - 从文本中搜索过滤器值
- node.js - 无法使用 typescript 和 sass 构建 next.js 应用程序
- html - AngularJS:如何从控制器引用表单的 $invalid 变量?
- java - 反应本机构建失败任务':app:checkDebugDuplicateClasses'的执行失败
- python - 多处理代码如何腌制地图功能?
- oracle - Oracle (godror) 打开的连接数超过了允许的最大值