javascript - Mongoose 中未处理的PromiseRejection警告

标签 javascript node.js mongodb mongoose

我有这样的类别架构:

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

关于javascript - Mongoose 中未处理的PromiseRejection警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429042/

相关文章:

javascript - 这是一个有效的 React HoC 用例吗?

javascript - 浏览器中的事件循环和任务队列之间有区别吗?

javascript - 使用 Express http-proxy 从 API 存储 token

javascript - Node.js 中的 Azure DocumentDB 存储过程执行现有的

node.js - 如何判断用户是否是第一次登录?

javascript - 加载本地文件时出现 "Cross origin requests are only supported for HTTP."错误

javascript - 在 Javascript 中操作 DOM 的简单方法

node.js - 在嵌套表中使用 dataloader-sequelize 显示特定列

javascript - 如何在一个 Angular 应用程序中访问两个 Mongo 数据库?

javascript - node.js mongoError 未授权管理员执行命令