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

后端 未结 2 1257
半阙折子戏
半阙折子戏 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);
         })
    

提交回复
热议问题