星空网 > 软件开发 > Java

在Mongoose中使用嵌套的populate处理数据

  假设有如下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

 




原标题:在Mongoose中使用嵌套的populate处理数据

关键词:Mongo

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

EORI税号:https://www.goluckyvip.com/tag/2489.html
shipout海外仓:https://www.goluckyvip.com/tag/24890.html
Shipper:https://www.goluckyvip.com/tag/24891.html
shipping discount:https://www.goluckyvip.com/tag/24892.html
ShippingEasy:https://www.goluckyvip.com/tag/24893.html
Shippo:https://www.goluckyvip.com/tag/24894.html
75通讯录|巨大人口红利下的朝阳品类!独家对谈印尼本地头部母婴品牌Mooimom:https://www.xlkjsw.com/news/90174.html
云蒙山风景区介绍-云蒙山风景区游玩攻略:https://www.vstour.cn/a/407228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流