0

I want to define a one-to-many relationship between my Category model and Product model.

product.js (Model)

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    price:{
        type:Number,
        required:true
    },
    description:{
        type:String,
        required:false
    },
    imageUrl:{
        type:String,
        required:true
    },
    categoryId:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Category'
    }
},
{timestamps:true})  

module.exports = mongoose.model('Product',productSchema)

category.js (Model)

const mongoose = require('mongoose');

const categorySchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    products:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Product'
    }]
},
{timestamps:true})  

module.exports = mongoose.model('Category',categorySchema)

My search function

exports.findCategoryWithProducts = (req, res, next) => {
    Category.findById(req.params.categoryId)
        .populate('products')
        .then(category => {
            res.status(200).json({ category: category })
        })
        .catch(err => console.log(err))
}

function result

{
    "category": {
        "products": [],
        "_id": "6058a54e79e9054d9f9e6821",
        "name": "Pc",
        "createdAt": "2021-03-22T14:10:22.509Z",
        "updatedAt": "2021-03-22T14:10:22.509Z",
        "__v": 0
    }
}

I have 2 products in this category but it gives me empty products array. Am I missing something? version "mongoose": "^5.12.1",

  • better to use aggregrate function instead of findbyId function. You can check docs : https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ – Dhaval Darji Mar 25 '21 at 16:46
  • I would recommend not doing this because if you have a category like phones and you have tons of phone then it will be very hard to update and delete and not intuitive. But in any case, try using populate({path: "products"}) let me know if it works. – Namit Piriya Mar 25 '21 at 17:50

2 Answers2

0

Try to do that

exports.findCategoryWithProducts = (req, res, next) => {
  Category.findById(req.params.categoryId).populate('products').execPopulate()
    .then(category => {
      res.status(200).json({
        category: category
      })
    }).catch(err => console.log(err))
}
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • 1
    { "message": "Category.findById(...).populate(...).execPopulate is not a function" } – Serkan Eris Mar 25 '21 at 17:42
  • 1
    of course it's a function i used to work with it check that [link]https://mongoosejs.com/docs/api/document.html#document_Document-execPopulate – hamzaSa Mar 25 '21 at 18:13
0

I thought Mongoose ORM is automatically find relation with category and products. Mongoose needed product array on category to find relationship. So I added to products array to category doc. Now its working. tnx all..