Mongoose/mongoDB查询加入..但我来自sql背景

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)

  • 非常有趣我会应用它并看看它是如何工作的,但你提到的第二个看起来就像我需要的那样. (2认同)
  • 我有点不知所措,因为它如何知道在哪里“加入”。那是ref属性的目的吗?猫鼬的填充对象是否基于ref为Project来查找ProjectSchema,这是否意味着需要遵守严格的命名约定? (2认同)