I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB.
However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category')". Interestingly, the console.log shows an array with categories first before throwing the error "cannot read"..
As a beginner in express js, I would appreciate any hints or tips from experienced users.
exports.articleDetail = async (req, res) => {
const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');
const articlecategories = article.category
categories = []
for(let i=0;i<articlecategories.length;i++){
const category = articlecategories[i]
categories.push(category._id)
}
console.log(categories)
const relatedarticles = await Article.find({ category : { $all : categories }})
console.log(article);
res.render('article', { article, relatedarticles })
}
Edit
Thank You all for answers. I have a solution. Problem is that when loop through article categories, I get no category ID but new ObjectId: new ObjectId("636bc1c64f7470f2557b61d7")
To let this work, I must use .toString() and get only Id and then push this Id to array.
This is working code:
exports.articleDetail = async (req, res) => {
const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');
categories = []
for(let i=0;i<article.category.length;i++){
const category = article.category[i]
const catid = category._id.toString()
categories.push(catid)
}
console.log(categories)
const articles = await Article.find({category: { $all: categories }}).populate('author')
res.render('article', { article, articles })
}