Mongoose model.Populate()

Quick start using mongooses populate() method!

Angelo Poole
2 min readSep 12, 2020
Photo by Dušan Smetana on Unsplash

While trying to learn NoSQL databases I’ve come upon the problem of “how do I reference another ‘table’ in MongoDB”, well the solution is pretty simple, populate()!

User schema
Profile schema

Mongooses populate() function is a real handy dandy way of letting you reference documents in other collections. I’ll go ahead and use a project I’m working on as an example of its usage.

populate function usage

Here we have two schemas that create a User and a Profile model. Notice that in the profile schema we create an object labeled user and give it a reference of our model “user”. This tells mongoose what we will populate this field with when we use .populate()

In this routing example, we will use populate() in order to give this profile access to the user. Currently, we have access to the user.id object from the request object due to the auth middleware that I created. We will use this to find the profile that matches the user’s id and populate the profile with the users’ current name and avatar. populate() will take in the model that you wish to reference. It can also take in an array of the fields that you want it to populate with. In this case, I only need the name and avatar of the user. Now if I were to send off a request to this route I would get back a profile object with a filled-out user object.

And there we have it, a quick example of how to use Model.populate(), this is only a small example of the things that you can accomplish with populate and I would highly recommend checking out mongoose documentation on it.

--

--

Angelo Poole
Angelo Poole

Written by Angelo Poole

Software engineer, Graduate of Flatiron school. Currently volunteering! Looking to talk to fellow engineers, please send me a message!

No responses yet