參考地址:http://ronaldroe.com/populating-multiple-fields-and-levels-with-mongoose/
文字版本
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方法,對關聯數據進行查詢
當查詢機器時,需要查詢更多了
最終查詢出來的