looking for some solutions? You are welcome.

SOLVED: Join two collection in mongoose using nodejs

Madhumitha:

I want to join two collection in MongoDB. I have two collections 1. student 2. course.

student collection:

enter image description here

course collection

enter image description here

I tried some code but that is not working.

This is my code

student.js

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

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

This is 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);

Result: enter image description here



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent