Mongoose/mongoDB 查询加入.. 但我来自 sql 背景 [英] Mongoose/mongoDB query joins.. but I come from a sql background

查看:35
本文介绍了Mongoose/mongoDB 查询加入.. 但我来自 sql 背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 sql 背景,所以在连接表的 sql 中编写查询非常简单,但我想我在 mongoose/mongodb 中遗漏了这一点

I coming from a sql background so writing queries in sql where I join tables is quite simple but I guess I am missing that in mongoose/mongodb

基本上我知道 Subscriber_ID(映射到用户集合中的文档)

Basically I know the Subscriber_ID (which maps to a document in the User Collection)

我想拉出项目组,包含用户所属的所有项目,所以如果我在 pseduo sql 中编写它会像

I want to pull the project group, with all the projects that the user belongs to so if I was to write this in pseduo sql it would be like

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 中进行类似的连接,因为类型映射到架构对吗?

There must be a way to do similiar joins in mongoose/mongodb because the type is mapping to a schema right?

我的架构.....

项目组架构

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' }]
});

然后您可以执行以下操作:

Then you can do the following:

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);
     })

这篇关于Mongoose/mongoDB 查询加入.. 但我来自 sql 背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆