How to join query in mongodb?

后端 未结 10 2227
情深已故
情深已故 2020-11-29 03:22

I have user document collection like this:

User {
   id:\"001\"
   name:\"John\",
   age:30,
   friends:[\"userId1\",\"userId2\",\"userId3\"....]
}
         


        
10条回答
  •  情话喂你
    2020-11-29 03:54

    You can use in Moongoose JS .populate() and { populate : { path : 'field' } }. Example:

    Models:

     mongoose.model('users', new Schema({
            name:String,
            status: true,
            friends: [{type: Schema.Types.ObjectId, ref:'users'}], 
            posts: [{type: Schema.Types.ObjectId, ref:'posts'}], 
    
        }));
     mongoose.model('posts', new Schema({
                description: String,
                comments: [{type: Schema.Types.ObjectId, ref:'comments'}], 
    
            }));
     mongoose.model('comments', new Schema({
                comment:String,
                status: true
    
            }));
    

    If you want to see your friends' posts, you can use this.

    Users.find().                    //Collection 1
            populate({path:'friends',   //Collection 2
            populate:{path:'posts'   //Collection 3
            }})
        .exec();
    

    If you want to see your friends' posts and also bring all the comments, you can use this and too, you can indentify the collection if this not find and the query is wrong.

     Users.find().                                    //Collection 1
            populate({path:'friends',                 //Collection 2
            populate:{path:'posts',                   //Collection 3
            populate:{path:'commets, model:Collection'//Collection 4 and more
            }}})
        .exec();
    

    And to finish, if you want get only some fields of some Collection, you can use the propiertie select Example:

    Users.find().                                    
            populate({path:'friends', select:'name status friends'                  
            populate:{path:'comments'               
            }})
        .exec();
    

提交回复
热议问题