博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nodejs mongoose populate 多层模型
阅读量:6543 次
发布时间:2019-06-24

本文共 2192 字,大约阅读时间需要 7 分钟。

参考地址:

文字版本

Mongoose, the popular MongoDB library for NodeJS is incredibly robust and relatively easy to pick up. Its documentation, however leaves a little to be desired.To attain functionality similar to join functionality present in relational databases, Mongoose provides a method called populate(). Used in conjunction with the ref schema property, data can be pulled in from other documents in place of an id. The process is fairly straightforward. However, what Automattic’s documentation doesn’t explain is how to populate multiple paths, and the documentation for multiple levels leaves much to be desired.The documentation does point out that chaining multiple populate functions won’t work. How, then can this be done? Multiple paths may be populated by creating a space-separated list. Note the emphasis, because comma-separated lists do not work. By way of example:// Doesn't work - will only populate 'friends'Users.findOne({/* query here */}).populate('address').populate('friends');// Works,多个关联字段Users.findOne({/* query here */}).populate('address friends');Now, what if we wanted to populate the friends’ addresses? As explained in the docs, you would nest another populate by passing an object to the method, and adding another populate as a property. That was pretty confusing to me, but here’s what it means:// This time, we're not passing a string, but an object to populate(),多层关联Users.findOne({/* query here */}).populate({  path: 'address friends', // The string we passed in before  populate: {    path: 'address' // This will populate the friends' addresses  }});The first level of items to populate is passed in a key called path. The next level items to populate are passed as a new populate object. This can be continued on down the line as necessary. Each populate will have a path key/value pair, and if there’s another level of things to populate, those are passed in a populate key/value pair.

 

 

需求是因为有三个模型,工厂、车间、机器,关联关系是

工厂=》车间=》机器

即一个工厂对应多个车间,一个车间对应多个机器

所以在设计模型时,设计成,工厂模型、车间模型、机器模型,并在车间模型中保存了工厂模型的ID,也在机器模型中保存了车间模型的ID

对应的模拟代码是

 

那么对应的查询中,工厂只需要查询自己即可

车间需要关联至工厂,那么需要增加populate方法,对关联数据进行查询

当查询机器时,需要查询更多了

最终查询出来的

 

转载于:https://www.cnblogs.com/weschen/p/10635334.html

你可能感兴趣的文章
JavaScript实用手册
查看>>
dpkg参数
查看>>
AS3!INT
查看>>
简述思科、华为交换机型号字母代表的意思
查看>>
memcache--mysql测试
查看>>
拷贝构造函数、拷贝函数、析构函数
查看>>
实战CGLib系列之proxy篇(一):方法拦截MethodInterceptor
查看>>
php 字符串截取
查看>>
ttcn-3
查看>>
00.java虚拟机的基本结构概念
查看>>
深入浅出 ES6:ES6 与 Babel - Broccoli 的联用
查看>>
ThreadLocal使用出现的问题
查看>>
关于十六进制和八进制负数的问题
查看>>
连接池并发的实现原理
查看>>
创建Pch预编译文件
查看>>
阿里云Centos配置iptables防火墙
查看>>
UML类图几种关系的总结
查看>>
PHP面试题汇总
查看>>
LeetCode (11): Container With Most Water
查看>>
【技巧】easyUI的datagrid,如何在翻页以后仍能记录被选中的行
查看>>