简体   繁体   中英

How to perform inner join in mongoose

I was googling for last two days but no success. I need to perform inner join in mongoose with two schema but not getting response my other collection. My question is what am I missing in my code? Please help me with this.

I want to get result of class and subjects also.

  exports.classSubjectList = async (req, res, next) => {
  const obj = await ClassSubject.find().populate('classmodel').exec();
  res.status(200).json({
        success: true,
        response: obj
      });
};

//ClassSubjectModel

const mongoose = require('mongoose');
mongoose.Promise = global.Promise 
const Schema = mongoose.Schema
const classModel  = require('../class/classModel');
const subjectModel  = require('../subject/subjectModel');

var classsubject = new Schema({    
    ClassId: String,
    SubjectId : String,
    IsShow: { type: Boolean, default : true},   
    classmodel: { type: mongoose.Schema.Types.ObjectId, ref: classModel },
    subjectmodel: { type: mongoose.Schema.Types.ObjectId, ref: subjectModel },

});

//Class Model

const mongoose = require('mongoose');
mongoose.Promise = global.Promise 
const Schema = mongoose.Schema

var classinfo = new Schema({    
    ClassName: String,
    IsShow: { type: Boolean, default : true},   

});


module.exports = mongoose.model('classinfo', classinfo);

//SUBJECT Model

const mongoose = require('mongoose');
mongoose.Promise = global.Promise 
const Schema = mongoose.Schema

var subject = new Schema({    
    SubjectName: String,
    IsShow: Boolean,   

});


module.exports = mongoose.model('subject', subject);

result

[
        {
            "IsShow": true,
            "_id": "5e1efc0f354849246c472cfe",
            "SubjectId": "5e1da60bf52acb30b87e92c4",
            "ClassId": "5e1ec13ed777bf28d01e2481",          
            "__v": 0
        }]

You should define ref as the name of your schema & not the object reference

Do it like this

classmodel: { type: mongoose.Schema.Types.ObjectId, ref: 'classinfo' } 
subjectmodel: { type: mongoose.Schema.Types.ObjectId, ref: 'subject' },
// here 'classinfo' & 'subject' are the names you defined your schema with 

You should populate both if you want a proper inner join

const obj = await ClassSubject.find().populate('classmodel').populate('subject').exec();

You must store ids of class & reference in classmodel & subjectmodel key of your document for this to work

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM