Mongoose的populate 查询

在使用MongoDB的时候 使用populate 方法来代替关系型数据库的join,在定义一个Schema的时候可以指定其中的字段(属性)是另一个Schema的引用,在查询文档的时候就可以使用populate方法通过引用Schema和id找到关联的另一个文档或者文档的指定字段值。下面是一个简单的例子。

//引入包
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名
    }
})
// 模式添加方法  根据学生id 去查询班级信息
StudentSchema.statics = {
    findClazzNameByStudentId:function(studentId, callback){
            return this
                .findOne({_id : studentId}).populate('clazzID')  // 关联查询
                .exec(callback)
        }
}

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

// 模型model
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');
})*/

//在上面 学生模式,定义了findClazzNameByStudentId 方法 通过学生id 去查询其班级信息
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);              // 数据库报错信息
}

参考地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值