Search code examples
node.jsmongoosemongoose-schemamongoose-populate

Trying to populate an object inside another object that is inside another object (NODE.JS)


This function gets a specific "process" and shows the following information in json: (POSTMAN)

{
    "process": {
        "_id": "5c18e8d1d4817811839d43d2",
        "name": "Dyeing",
        "colour": {
            "_id": "5c18c972b39bb20769288e8f",
            "name": "azul",
            "category": "5c18c09f4c6baf05ea621bca",
            "__v": 0
        },
        "__v": 0
    },
    "request": {
        "type": "GET",
        "url": "http://localhost:3000/process"
    }
}

Process controller function

   exports.process_get_process = (req, res, next) => {
    Process.findById(req.params.processId)
      .populate("colour")
      .populate("category")
      .exec()
      .then(process => {
        if (!process) {
          return res.status(404).json({
            message: "Process not found"
          });
        }
        res.status(200).json({
          process: process,
          request: {
            type: "GET",
            url: "http://localhost:3000/process"
          }
        });
      })
      .catch(err => {
        res.status(500).json({
          error: err
        });
      });
};

The model for the "process" is the following schema:

const mongoose = require('mongoose');

const processSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    price: { type: Number, required: false },
    colour: { type: mongoose.Schema.Types.ObjectId, ref: 'Colour', required: false },
});

module.exports = mongoose.model('Process', processSchema);

This is the Colour model: As you can see the object "category" is inside "colour" and i want to show him in the "process" object as well.

const mongoose = require('mongoose');

const colourSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true },
});

module.exports = mongoose.model('Colour', colourSchema);

Problem: Inside the "colour" exist a "category" object, but only shows the category id, and i want him to show all the category information. How can I populate it?


Solution

  • You can specify that as options for the populate function.

    Process.findById(req.params.processId)
          .populate({
               path: 'colour',
               populate: { path: 'category' }
           })
          .exec()