首页 > 解决方案 > 使用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);

结果: 在此处输入图像描述

标签: node.jsmongodbjoinmongoosemongoose-schema

解决方案


你需要这样查询:

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课程收藏中的字段。


推荐阅读