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

后端 未结 2 1230
半阙折子戏
半阙折子戏 2020-11-27 02:43

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 S

相关标签:
2条回答
  • 2020-11-27 03:29

    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);
         })
    
    0 讨论(0)
  • 2020-11-27 03:30

    There are no joins in Mongodb. This question I think is a good reference:

    MongoDB and "joins"

    To summarize, different strategies have to be adopted with mongodb for problems that would be addressed via joins in relational DBs. I would say you mainly end-up doing one of these two things:

    • Embedding: You embed information in a single document that would in a relational DB be distributed amongst different tables.
    • Joining information client-side: When you need to use information from several places, you query many times and then put the pieces together in your client.
    0 讨论(0)
提交回复
热议问题