使用nodejs在猫鼬中加入两个集合

时间:2019-03-11 06:50:01

标签: node.js mongodb join mongoose mongoose-schema

我想加入MongoDB中的两个收藏夹。我有两个收藏1.学生2.课程。

学生集合:

enter image description here

课程收藏

enter image description here

我尝试了一些代码,但是没有用。

这是我的代码

student.js

router.get('/student/:id', function(req, res){

    Student.find({_id:req.params.id}, function(err, user){
        res.send(user);
    })
})

这是 Schema

student.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);

结果: enter image description here

1 个答案:

答案 0 :(得分:1)

您需要这样查询:

  

findOne :查找单个文档(返回对象{})

     

查找:查找多个文档(返回数组[])

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字段。

相关问题