美文网首页技术文档
Mongoose populate多表关联查询

Mongoose populate多表关联查询

作者: real_ting | 来源:发表于2018-04-04 18:30 被阅读0次

    关于mongoose的关联查询,举例说明:

    1. 初始化3个Schema和3个model
    var studentSchema = new Schema({
        name  : String,
        age   : String,
        school: {
            type: Schema.Types.ObjectId,
            ref : 'school'
        }
    });
    var schoolSchema = new Schema({
        name    : String,
        students: [
            {
                type: Schema.Types.ObjectId,
                ref : 'student'
            }
        ],
        city    : {
            type: Schema.Types.ObjectId,
            ref : 'city'
        }
    });
    var citySchema = new Schema({
        name  : String,
        school: [
            {
                type: Schema.Types.ObjectId,
                ref : 'school'
            }
        ]
    });
    var Student = mongoose.model('student', studentSchema);
    var School = mongoose.model("school", schoolSchema);
    var City = mongoose.model("city", citySchema);
    
    1. 初始化数据
    var city = new City({
        name  : '北京',
        school: []
    });
    
    city.save(function (err, city) {
        var school = new School({
            name    : 'Test',
            students: [],
            city    : city._id
        });
        school.save(function (err, school) {
            var student = new Student({
                name  : 'Tom',
                age   : 20,
                school: school._id
            });
            student.save();
        });
    });
    
    1. 进行关联查询,进行查询的时候要把初始化的数据注释掉
    Student.findOne({name: 'Tom'})
           .populate({
               path: 'school',
               populate: {path: 'city'}
           })
           .exec(function (err, data) {
              console.log(data.name + ' 所在学校为:' + data.school.name + ",所在城市为:" + data.school.city.name);
    })
    
    1. 结果
    Tom 所在学校为:Test,所在城市为:北京
    

    相关文章

      网友评论

        本文标题:Mongoose populate多表关联查询

        本文链接:https://www.haomeiwen.com/subject/tyllhftx.html