'Getting error in query population in mongoose v6
I want to populate the category field in product schema.
The code for my product schema is
const mongoose = require('mongoose');
const {ObjectId} = mongoose.Schema
const productSchema = new mongoose.Schema({
name :{
type:String,
required : true,
trim : true,
maxlength : 32,
},
description : {
type:String,
required : true,
trim : true,
maxlength : 2000,
},
price : {
type : Number,
required : true,
maxlength :32
},
category : {
type : ObjectId,
ref : "Category",
required : true
},
stock : {
type : Number,
},
sold : {
type :Number,
default : 0
},
photo : {
data : Buffer,
contentType : String
}
},{timestamps:true})
module.exports = mongoose.model("Product",productSchema);
And The code which i am using to populate the category field is
exports.getAllProducts = (req,res)=>{
let no_of_products = req.query.limit? parseInt(req.query.limit):8;
let sortBy = req.query.sortBy?req.query.sortBy : "price"
Product.find()
.populate("catgeory")
.select("-photo")
.sort({sortBy:1})
.limit(no_of_products)
.exec((err,products)=>{
if(err){
console.log(err);
return res.status(400).json({
error : "some error occured"
})
}
})
}
But this code is giving me error which say
cannot populate path Catgeory because it is not in your schema. Set the strictPopulate option to false to override.
I have read documentation but i am unable to alter my code . Kindly help me with this issue.
Solution 1:[1]
check the Product databases table that you have category keys and you should know that the object Id is correct and it comes from the category table if not you should drop the database or drop the product collection and create the new one
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammed Hesham Farhan |
