node

How to use Populate in mongoose


In this article, you will learn about the mongoose populate.

From version 3.2 or above, MongoDB has the join, like $lookup aggregation operator. But in mongoose, you will get a more powerful alternative which name is populate(). It will let you reference documents in other collections. In mongoose, Populate is the way of replacing a path in the document with actual documents from other collections automatically.

Lets assume, you are working with two collections and schema – User and Blog. Now, you want a user by id with its blogs. But you have faced a situation which is you are getting the user document with his blog ids array instead of getting blog documents.

To overcome the situation you can simply use mongoose populate in you schema and collection. Follow the code below :

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
   name: String,
   email: String,
   blogs: [{ 
      type: mongoose.Schema.Types.ObjectId,
      ref: "Blog"
   }]
});

const BlogSchema = new Schema({
   title: String,
   user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
   },
   body: String,
})

const User = mongoose.model("User", UserSchema);
const Blog = mongoose.model("Blog", BlogSchema);

module.exports = {User, Blog}

// In your node js file
const User = require("path/to/userSchema");

User
   .findOne({_id: userId })
   .populate("blogs") // key to populate
   .then(user => {
      res.json(user); 
   });

/*
OUTPUT:
 {
    _id: userid, // It will be generated by mongoDB
    name: "Test",
    email: "test@gmail.com",
    blogs: [
        {
            _id: blogid, 
            title: "how to use populate in mongoose",
            body: "Mongoose populate is a powerful..."
        }
    ]
 }
*/

You can see how powerful mongoose populate method is and you can get your desired solution by using it.
Important : You need to keep in mind some key points while using mongoose populate. These are:

  1. The field will be null, if no document is found to populate.
  2. It will return an empty array, if documents are not found in the array.
  3. For populating multiple fields you can chain populate method.
  4. If you populate two populate methods for the same field. It will simply override the first one with second populate .

Note: ObjectId, Number, String, and Buffer are valid for use as refs. But you should use ObjectId unless you are working on complex or have a good reason for doing so.


Share on social media

//