關(guān)于mongoose的關(guān)聯(lián)查詢,舉例說(shuō)明:
- 初始化3個(gè)Schema和3個(gè)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);
- 初始化數(shù)據(jù)
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();
});
});
- 進(jìn)行關(guān)聯(lián)查詢,進(jìn)行查詢的時(shí)候要把初始化的數(shù)據(jù)注釋掉
Student.findOne({name: 'Tom'})
.populate({
path: 'school',
populate: {path: 'city'}
})
.exec(function (err, data) {
console.log(data.name + ' 所在學(xué)校為:' + data.school.name + ",所在城市為:" + data.school.city.name);
})
- 結(jié)果
Tom 所在學(xué)校為:Test旬渠,所在城市為:北京