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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM