nwk*_*ley 22 mongoose mongodb node.js
我来自一个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
Run Code Online (Sandbox Code Playgroud)
必须有一种方法可以在mongoose/mongodb中进行类似的连接,因为类型正在映射到模式吗?
我的架构.....
项目组架构
var ProjectGroupSchema = new Schema({
title : String
, projects : [ { type: Schema.Types.ObjectId, ref: 'Project' } ]
});
Run Code Online (Sandbox Code Playgroud)
项目架构
var ProjectSchema = new Schema({
title : {type : String, default : '', required : true}
, subscribers : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)
用户架构
var UserSchema = new Schema({
first_name : {type: String, required: true}
, last_name : {type: String, required: true}
});
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mic*_*Yin 54
你只有一步之遥!
项目组架构:
var ProjectGroupSchema = new Schema({
title : String
});
Run Code Online (Sandbox Code Playgroud)
项目架构:
var ProjectSchema = new Schema({
title : {type : String, default : '', required : true},
group : {type: Schema.Types.ObjectId, ref: 'ProjectGroup' },
_users : [{type: Schema.Types.ObjectId, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)
用户架构:
var UserSchema = new Schema({
first_name : {type: String, required: true},
last_name : {type: String, required: true},
subscribing : [{type: Schema.Types.ObjectId, ref: 'Project' }]
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作:
user.findById(req.userId)
.populate('subscribing')
.exec(function(err, user){
console.log(user.subscribing);
})
Run Code Online (Sandbox Code Playgroud)
要么:
project.find({
subscriber : req.userId
})
.populate('subscriber')
.populate('group')
.exec(function(err, projects){
console.log(projects);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38014 次 |
| 最近记录: |