【问题标题】:How to perform inner join in mongoose如何在猫鼬中执行内部连接
【发布时间】:2020-01-17 20:47:44
【问题描述】:

过去两天我在谷歌上搜索,但没有成功。我需要使用两个模式在猫鼬中执行内部连接,但我的其他集合没有得到响应。 我的问题是我的代码中缺少什么?请帮我解决这个问题。

我也想得到班级和科目的成绩。

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

【问题讨论】:

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


    【解决方案1】:

    您应该将 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 您的文档的密钥以使其正常工作

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多