我来自sql背景,因此在连接表的sql中编写查询非常简单,但我想我在mongoose / mongodb中缺少它
基本上,我知道Subscriber_ID(映射到User Collection中的文档)
我想拉用户用户所属的所有项目的项目组,所以如果我要用pseduo sql编写它,就像
Select ProjectGroup.title, Project.Title FROM ProjectGroup, Project, User WHERE User.id = req.body.subscriber_id AND Project.subscriber_id = User.id AND ProjectGroup.project_id = Project.id
必须有一种方法可以在mongoose / mongodb中进行类似的联接,因为类型正在映射到架构,对吗?
我的模式.....
项目组架构
var ProjectGroupSchema = new Schema({ title : String , projects : [ { type: Schema.Types.ObjectId, ref: 'Project' } ] });
项目架构
var ProjectSchema = new Schema({ title : {type : String, default : '', required : true} , subscribers : [{ type: Schema.Types.ObjectId, ref: 'User' }] });
用户架构
var UserSchema = new Schema({ first_name : {type: String, required: true} , last_name : {type: String, required: true} });
谢谢!
您只有一步之遥!
项目组架构:
var ProjectGroupSchema = new Schema({ title : String });
项目架构:
var ProjectSchema = new Schema({ title : {type : String, default : '', required : true}, group : {type: Schema.Types.ObjectId, ref: 'ProjectGroup' }, _users : [{type: Schema.Types.ObjectId, ref: 'User' }] });
用户架构:
var UserSchema = new Schema({ first_name : {type: String, required: true}, last_name : {type: String, required: true}, subscribing : [{type: Schema.Types.ObjectId, ref: 'Project' }] });
然后,您可以执行以下操作:
user.findById(req.userId) .populate('subscribing') .exec(function(err, user){ console.log(user.subscribing); })
要么:
project.find({ subscriber : req.userId }) .populate('subscriber') .populate('group') .exec(function(err, projects){ console.log(projects); })