Mongoose中关联查询populate的使用

MongoDB中没有join的特性,因此无法使用join进行表的连接和关联查询,在Mongoose中封装了populate方法,在定义一个 Schema 的时候可以指定了其中的字段(属性)是另一个Schema的引用,在查询文档时就可以使用 populate 方法通过引用 Schema 和 id 找到关联的另一个文档或文档的指定字段值。下面是一个简单的栗子:

【场景】: 通过学生ID找到学生所在的班级,对应集合: 学生students、 班级clazzs 


var mongoose = require('mongoose')
var app = require('express')()
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')

// 定义学生模式
var StudentSchema = new mongoose.Schema({
name: String,
clazzID : {
type : mongoose.Schema.ObjectId,
ref : 'Clazz' // clazz的Model名
}
})
// 连表查询方法
StudentSchema.statics = {
findClazzNameByStudentId:function(studentId, callback){
return this
.findOne({_id : studentId}).populate('clazzID') // 关联查询
.exec(callback)
}
}

// 定义班级模式
var ClazzSchema = new mongoose.Schema({
clazzName: String
});

// 模型
var Student = mongoose.model('Student',StudentSchema)
var Clazz = mongoose.model('Clazz',ClazzSchema)

// 新建班级文档并保存
/*var clazz = new Clazz(
{
clazzName:'体育9班'
}
);
clazz.save(function (argument){
console.log('true');
});
*/

// 新建学生文档并保存
/*var student = new Student({
name : '马冬梅',
clazzID : '56e1440f508c947b0f32c16b' //体育3班的_id
})
student.save(function (err){
console.log('true');
})*/


Student.findClazzNameByStudentId('56e1446c64a8f59c0f866df3', function (err, student){
if(err) console.log(err);
console.log(student.name + " 在的班级: "+student.clazzID.clazzName);
/*通过studentID查询到对应的学生对象,并通过关联属性clazzID获取到对应classID的班级对象,
通过对象的clazzName属性返回班级名称*/
})

var logger = require('morgan');
if('development' === app.get('env')){
app.set('showStackError', true); // 输出报错信息
app.use(logger(':method :url :status')); // 输出信息领域
app.locals.pretty = true; // 源代码格式化
mongoose.set('debug', true); // 数据库报错信息
}



首先在数据库中插入一下几条班级的记录:

然后新建学生对象:

通过clazzID的值可以知道 马冬梅 的班级为 体育3班

 运行代码,通过studentID查询 学生所在的班级, 结果如下:

原文地址:https://www.cnblogs.com/adjk/p/8288961.html