here i am taking ref from category and sub category field from their database and want to populate the name of category and sub category but getting this error "Cannot read properties of undefined (reading 'populate')"
this.products.findOne({ _id: req.query.productId }, { createdAt: 0, updatedAt: 0, isActive: 0, isDeleted: 0, __v: 0 })
.exec(function (error, data) {
if (error) {
callback(error);
}
if (data && data.length == 0) {
return callback(false, common.errorMsg("NO Details FOUND"));
} else {
// return callback(false, common.successMsg("product list", data));
data=data.map(function(item){
return {
productId: item._id,
productName: item.productName,
storeName: item.createdBy.fullName,
categoryName:item.category.name,
subCategoryName:item.subCategory.name,
image: item.fabricType[0].style[0].images[0],
price: item.price
}
})
}
return callback(false, common.successMsg("product", data));
}).populate('createdBy').populate('category').populate('subCategory').lean()
The exec method returns a promise, so after that, you can't call the populate function. try this code:
this.products
.findOne(
{ _id: req.query.productId },
{ createdAt: 0, updatedAt: 0, isActive: 0, isDeleted: 0, __v: 0 },
)
.populate('createdBy')
.populate('category')
.populate('subCategory')
.lean()
.exec(function (error, data) {
// ...
})