 推荐工具
› RoboMongo
推荐书目
› 50 Tips and Tricks for MongoDB Developers
推荐工具
› RoboMongo
推荐书目
› 50 Tips and Tricks for MongoDB Developers我使用 apollo server 通过 mongoose 连接 mongodb 进行后台开发。 现在遇到了一个问题,一个 collection Components 的结构为:
Components {
	coreInformation {
    	reflowId: String
        type: String
        ...    
    }
	flowInformation {
    	owner: String
        user: String
        ...
    }
}
另一个 collection Vessels 的结构为:
Vessels	{
	imo: String
	name: String
}
在 Components.flowInformation.user 中存储的是 Vessels.imo, 现在前端是列表显示 components,需要得到 Vessels.name,在传统的数据库中,有联合查询,很容易搞定。 但是在 mongoDB 中没有,我看网上说可以用 Populate+ Ref 搞定,但是我的 user 是包在 flowInformation 这个对象中的,我没有看到相关的例子。请 V 友帮忙,该如何使用,或者有其它的办法。谢谢。
PS:并不想把 name 作为冗余数据也放到 component 中,因为会改变原有 document 结构,改动太大。
看来这个帖子要自己结贴了, 使用 mongoose 中的 virtual populate 功能可以实现联合查询,方法就是在schma里面要配置一下外键,具体可以参考 https://mongoosejs.com/docs/populate.html#populate-virtuals, 记得要加上 { toJSON: { virtuals: true }, toObject: { virtuals: true }}, 否则同样出不来。
我的schema代码:
componentSchema.virtual("vessel", {
  ref: "MongoVessel", // The model to use
  localField: "flowInformation.user", // Find people where `localField`
  foreignField: "imo", // is equal to `foreignField`
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false
});
|      1pifuant      2019-07-23 18:31:19 +08:00 mongo 不支持 join, 认命吧 | 
|      2jk1030      2019-07-23 18:38:58 +08:00 nosql | 
|  |      3lqzhgood      2019-07-23 18:50:16 +08:00 via Android  1 | 
|  |      5bankroft      2019-07-23 18:52:41 +08:00 via Android $lookup ? | 
|      6ilucio      2019-07-24 08:35:51 +08:00 via Android mongodb  4.0 后可以用 lookup 实现联合查询了 |