我有类似这样的类别架构:
var category_article_Schema = new Schema({
"article_id": { type: String, required: false, unique: false },
"category": String,
"article": { type: mongoose.Schema.Types.ObjectId, ref: 'article'},
});
var category_article_Schema = mongoose.model('category_article_Schema', category_article_Schema);
module.exports = category_article_Schema;
文章架构:
var articleSchema = new Schema({
"title": { type: String, required: true, unique: false },
"details": String,
"username": { type: String, required: true, unique: false },
"postImageUrl": String,
"url": String,
"categories": [String],
"created_at": { type: Date, default: Date.now }
});
var article = mongoose.model('article', articleSchema);
module.exports = article;
当我尝试使用populate方法根据类别获取文章时,我会遇到异常:UnhandledPromiseRejectionWarning: Unhandled promise rejection
function getPostByCategory(req, res, next) {
category_article_model.find({category: req.params.name})
.populate('article')
.exec()
.then(function(err, articlesByCategory) {
if(err) throw err;
console.log(articlesByCategory);
})
}
首先,可能是错误的原因是什么?为什么?我试着寻找答案,但在每种情况下问题都不同。
答案 0 :(得分:1)
重构
function getPostByCategory(req, res, next) {
category_article_model.find({category: req.params.name})
.populate('article')
.exec()
.then(function(err, articlesByCategory) {
if(err) throw err;
console.log(articlesByCategory);
})
}
到这个
function getPostByCategory(req, res, next) {
category_article_model.find({category: req.params.name})
.populate('article')
.exec()
.then(function(articlesByCategory) {
console.log(articlesByCategory);
})
.catch(function (err){
throw err; // or handle it
})
}