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",