Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Join in Mongo

Hey I want to know how we can join collections in mongo like we did in SQL using JOIN. In my code I'm using ths code for fetching data from collections users and posts.

/* GET user home page  */
router.get('/',mid.requireLogin,function(req,res,next){
    User.findOne({_id:req.session.userID})
        .exec(function(err,user){
            if(err){
                return next(mid.error("Problem in fetching records.Refresh page again"));
            }else {
                Post.find()
                    .exec(function(err,posts){
                        if(err){
                            return next(mid.error("Problem in fetching records.Refresh page again"));
                        }else{
                            let homeData = {name:user.username,followers:425,followings:22,posts:122,profile:user.userimage,stories:posts};
                            return res.render('home',homeData);
                        }
                    });

            }
    });

});

Is this code is OK to fetch data from multiple collection ?

1 Answer

Hi,

This is a quite extensive topic so I'll give you just the basis. Take a look at two schemas I've made some time ago for a blog. One is for an image/video file and one is for post file. Obviously, you can add images to posts so I had to make some reference in my post db to the media file.

const mediaSchema = mongoose.Schema({
  originalname: String,
  destination: String,
  filename: String,
  path: String,
  relativePath: String,
  uploaded: Date,
  uploadedBy: String,
  category: [String],
  isActive: Boolean
});
const postSchema = mongoose.Schema({
  title: String,
  datePublished: {type: Date, default: Date.now()},
  dateEdited: {type: Date, default: Date.now()},
  content: String,
  by: String,
  isActive: Boolean,
  attachedImages: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Media'
  }]
});

As you can see in my postSchema I have an array with references to _ids from the media schema. So while sending post I'm also sending an array of _ids of media attached. Now if I want to retrieve a post with all the data I use:

Post.find({isActive: true})
   .populate('attachedImages')
   .exec(function (error, posts) {
      if (!error) {
    // making things with data

And I get my post and all the data of my Media like this:

{
    _id: "56d2e8f26aede6dbdd1ed4f3",
    title: "it's a title",
    content: "this is content",
    by: "admin",
    isActive: true,
    attachedImages: [{
        _id: "5706976076dc5e3f03f8339e",
        originalname: "8804177930521706392_n.jpg",
        destination: "public/dist/uploads/2016/04",
        filename: "1460049760614.jpg",
        path: "public/dist/uploads/2016/04/1460049760614.jpg",
        relativePath: "/uploads/2016/04/1460049760614.jpg",
        uploaded: "2016-04-07T17:22:40.627Z",
        uploadedBy: "admin",
        isActive: true,
        __v: 0,
        category: [
            "funny"
        ]
    }],
    dateEdited: "2016-04-07T19:36:30.401Z",
    datePublished: "2016-02-28T12:32:50.803Z"
}

You should go to the mongoose docs and read more about populate and topics related.

Hope that helps ;) Cheers!