UnhandledPromiseRejectionWarning

UnhandledPromiseRejectionWarning

This question already has answers here:
How to resolve UnhandledPromiseRejectionWarning in mongoose?
                            
                                (4个答案)
                            
                    
                2年前关闭。
        

    

我有这样的类别架构:

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;


当我尝试使用填充方法获取基于类别的文章时,出现异常: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);
    })
}


首先,错误的原因可能是什么?为什么?我尝试寻找答案,但每种情况下的问题都不同。

最佳答案

重构

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

10-07 18:00