Mongoose中关联查询populate的使用
2016-03-10 18:30
429 查看
MongoDB中没有join的特性,因此无法使用join进行表的连接和关联查询,在Mongoose中封装了populate方法,在定义一个 Schema 的时候可以指定了其中的字段(属性)是另一个Schema的引用,在查询文档时就可以使用 populate 方法通过引用 Schema 和 id 找到关联的另一个文档或文档的指定字段值。下面是一个简单的栗子:
【场景】: 通过学生ID找到学生所在的班级,对应集合: 学生students、 班级clazzs
首先在数据库中插入一下几条班级的记录:
然后新建学生对象:
通过clazzID的值可以知道 马冬梅 的班级为 体育3班
运行代码,通过studentID查询 学生所在的班级, 结果如下:
【场景】: 通过学生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查询 学生所在的班级, 结果如下:
相关文章推荐
- Linux 搭建 Objective-C开发环境
- 搭建Hadoop环境(二)
- 分页查询的两种方法(双top 双order 和 row_number() over ())
- Nginx:Purge,ngx_cache_purge模块
- Photoshop软件破解补丁安装方法
- Kali linux安装漏洞扫描工具Nessus指南
- S2SM项目tomcat启动停在Initializing Spring root WebApplicationContext
- Linux最常用指令及快捷键 Linux学习笔记
- 20135202闫佳歆--week3 跟踪分析Linux内核的启动过程--实验及总结
- shell相关注意点
- Hadoop在运行几个T数据量时报堆内存溢出
- popupwindow里含有listview,显示在控件上方
- 基于kubernetes构建Docker集群管理详解
- Linux基础--文件查找
- 在Linux服务器上配置phpMyAdmin
- Hadoop2.7.2分布式部署3(安装部署hadoop分布式)
- openfire内存设置
- linux上python2.7.11 和 3.6.2 编译安装时系统要预先安装的包(centos 用 yum安装即可)
- shell编程-数组
- linux修改用户打开文件数量的限制