iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > node.js >mongoose中利用populate处理嵌套的方法
  • 214
分享到

mongoose中利用populate处理嵌套的方法

嵌套方法mongoose 2022-06-04 17:06:20 214人浏览 八月长安
摘要

前言 nodejs在使用mongdb数据库中经常会使用到嵌套,比如一个多级分类等。这里我使用学校-->学院-->学生来展示使用populate处理嵌套。 定义modal 在模式中,我们需要使用

前言

nodejs在使用mongdb数据库中经常会使用到嵌套,比如一个多级分类等。这里我使用学校-->学院-->学生来展示使用populate处理嵌套。

定义modal

在模式中,我们需要使用Schema.ObjectId来表示要指向数据在mongoDB数据库中的_id。

学校

在学校的Schema中,colleges属性是要包含的学院的_id属性数组


var SchoolSchema = new Schema({
 name: String,
 colleges: [{
 type: Schema.ObjectId,
 ref: 'College'
 }],
 createTime: {
 type: Date,
 default: Date.now()
 }
});
var School = monGoose.model('School', SchoolSchema);

学院


var CollegeSchema = new Schema({
 name: String,
 students: [{
 type: Schema.ObjectId,
 ref: 'Student'
 }],
 createTime: {
 type: Date,
 default: Date.now()
 }
});
var College = mongoose.model('College', CollegeSchema);

学生


var StudentSchema = new Schema({
 name: String,
 sex: String,
 age: Number,
 createTime: {
 type: Date,
 default: Date.now()
 }
});
var Student = mongoose.model('Student', StudentSchema);

查找

直接查找

查找学校并找到指向的学院


School
 .find()
 .populate('colleges', ['_id','name'])
 .exec((err, schools) => {
 if (err) {
 console.log(err)
 }
 console.log(schools)
 })

populate的第一个参数是学校表中需要指向学院表的属性,即colleges;第二个参数为要在学院中查找的属性。如果不填写第二个参数,则默认全都查出。

这样查找出的结果中,学院的学生属性是该学院包含的学生的_id属性。如果需要都查找出来需要使用嵌套populate。

嵌套


School
 .find()
 .populate({
 path: 'colleges',
 select: ['_id', 'name'],
 // model: 'College',
 populate: {
 path: 'students',
 select: ['_id', 'name']
 // model: 'Student'
 }
 })
 .sort({
 createTime: -1
 }).exec(function(err, schools) {
 if (err) {
 console.log(err)
 }
 });

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程网的支持。

--结束END--

本文标题: mongoose中利用populate处理嵌套的方法

本文链接: https://www.lsjlt.com/news/12583.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作