Mongoose多表查询

文章来自
两个表关联查询aggregate
多个表关联查询aggregate
populate多表关联查询

多表查询的两个方式
一个是aggregate聚合
一个是populate

Schema的外表连接应该有个ref字段表示去那个表查

populate

var Schema = monogoose.Schema;

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 : 'students'
        }
    ],
    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);

// 存点数据,可以多存几条
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();
    });
});

// 这个需要先注释,先把数据存好,再把存数据的方法注释,再查
Student.find({name: 'Tom'})
       .populate({
           path: 'school',
           populate: {
              path: 'city',
           }
       })
       .exec(function (err, data) {
          console.log(data);
       })
原文地址:https://www.cnblogs.com/pengdt/p/12240488.html