簡體   English   中英

如何在貓鼬中執行內連接

[英]How to perform inner join in mongoose

我在谷歌上搜索了兩天,但沒有成功。 我需要使用兩個模式在 mongoose 中執行內部連接,但沒有得到我的其他集合的響應。 我的問題是我的代碼中缺少什么? 請幫我解決一下這個。

我也想得到課堂和科目的結果。

  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 },

});

//類模型

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

//主題模型

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

結果

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

您應該將 ref 定義為架構的名稱而不是對象引用

像這樣做

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 

如果你想要一個適當的內部連接,你應該填充兩者

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

您必須在文檔的 classmodel 和 subjectmodel 鍵中存儲類和引用的 id 才能使其工作

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM