Express js相关文章-错误无法读取null属性



我尝试根据类别显示相关文章。我使用mongoose从MongoDB查询东西。

当我尝试下面的代码时,我得到了错误&;TypeError: Cannot read properties of null (reading 'category')&;但是console.log from articlecategories首先显示带有类别的数组,然后抛出错误&;cannot read&;…

我是一个初学者在express js,也许有人给我一个提示。

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 })
}

编辑

谢谢大家的回答。我有办法了。问题是,当循环通过文章类别,我没有得到类别ID,但新的ObjectId:新的ObjectId("636bc1c64f7470f2557b61d7")

要让这个工作,我必须使用.toString()并且只获取Id,然后将这个Id压入数组。

这是工作代码:

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 })
}

可能由于无法找到对象,您对await Article.findOne的调用仅返回null。

你应该检查是否有任何发现,如果没有,直接返回一个错误,像这样:

exports.articleDetail = async (req, res) => {
const article = await Article.findOne({ slug: req.params.slug }).populate('category').populate('author');
if ( !article ) return res.status(404).json(/* include your error object here */);
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 })
}

相关内容

最新更新