Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

node.js - Mongoose/mongoDB query joins.. but I come from a sql background

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

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

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

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

My Schemas.....

Project Group Schema

var ProjectGroupSchema = new Schema({
    title             : String
  , projects          : [ { type: Schema.Types.ObjectId, ref: 'Project' } ]
});

Project Schema

var ProjectSchema = new Schema({
    title         : {type : String, default : '', required : true}
  , subscribers   : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

User Schema

var UserSchema = new Schema({
    first_name    : {type: String, required: true}
  , last_name     : {type: String, required: true}
});

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are just one step away!

Project Group Schema:

var ProjectGroupSchema = new Schema({
    title             : String
});

Project Schema:

var ProjectSchema = new Schema({
    title         : {type : String, default : '', required : true},
    group         : {type: Schema.Types.ObjectId, ref: 'ProjectGroup' },
    _users    : [{type: Schema.Types.ObjectId, ref: 'User' }]
});

User Schema:

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

Or:

project.find({
        subscriber : req.userId
      })
     .populate('subscriber')
     .populate('group')
     .exec(function(err, projects){
          console.log(projects);
     })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...