假設有如下mongodb的schema定義: drawApply = new Schema({ salesId: { type: Schema.ObjectId, ref: 'sales' }, money: Number, status: { type: Number, default: 0 },
假設有如下mongodb的schema定義:
drawApply = new Schema({ salesId: { type: Schema.ObjectId, ref: 'sales' }, money: Number, status: { type: Number, default: 0 }, createTime: { type: Date, default: Date.now } }); sales = new Schema({ name: { type: String, required: true, unique: true }, pwd: String, phone: String, merchant: { type: Schema.ObjectId, ref: 'merchant' }, status: { type: Number, default: 0 } }); merchant = new Schema({ name: String, sname: String, type: String });
表drawApply的salesId屬性指定表sales的_id,表sales的屬性merchant指定表merchant的_id。這是一種嵌套級聯的關係。
查找drawApply表的數據,並同時返回對應的sales表的數據,可以使用下麵的方法:
drawApply.find().populate('salesId', '_id name phone merchant').sort({createTime: -1}).exec(function(err, list) { // list of drawApplies with salesIds populated });
返回的結果中除了drawApply表的數據外,還會包含salesId中_id,name,phone,merchant四個屬性的值。但是merchant屬性的值是以ObjectId的形式顯示的,如果想知道對應的merchant其它屬性的值,則需要使用到嵌套的populate。代碼如下:
drawApply.find().populate({ path: 'salesId', select: '_id name phone merchant', model: 'sales', populate: { path: 'merchant', select: '_id sname', model: 'merchant' }).sort({createTime: -1}).exec(function(err, list) { // list of drawApplies with salesIds populated and merchant populated });
如果drawApply表中還存在其它ObjectId類型的欄位,則可以在populate方法後面繼續跟其它的populate,使用方法相同,如:
drawApply.find().populate({ path: 'salesId', select: '_id name phone merchant', model: 'sales', populate: { path: 'merchant', select: '_id sname', model: 'merchant' }) .populate('approver', 'name') .populate('operator', 'name') .sort({createTime: -1}).exec(function(err, list) { // list of drawApplies with salesIds populated and merchant populated });
有關populate的具體用法可以參考mongoose的官方文檔http://mongoosejs.com/docs/populate.html#deep-populate