如何解决猫鼬中的 UnhandledPromiseRejectionWarning? [英] How to resolve UnhandledPromiseRejectionWarning in mongoose?

查看:19
本文介绍了如何解决猫鼬中的 UnhandledPromiseRejectionWarning?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mongoose 获取数据.

I'm trying to fetch data using mongoose.

因此,每次我必须从 api 获取帖子时 -- localhost:3000/api/posts -- 我都会收到无法解密的错误.

So everytime i got to fetch the posts from the api -- localhost:3000/api/posts -- i get the foll error that i am unable to decypher.

(node:12100) UnhandledPromiseRejectionWarning:未处理的承诺拒绝 (r
弹出 id: 1): [MongoError: connect ETIMEDOUT xxxx]

(node:12100) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r
ejection id: 1): [MongoError: connect ETIMEDOUT xxxx]

下面是我在 api.js 文件中的代码.如果您能提供有关我哪里出错的指导,我将不胜感激.

The foll is my code in the api.js file. I'd appreciate if you can provide guidance on where i am going wrong with this.

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const post = require('../models/post');

const db = "mongodb://<dbuser>:<dbpassword>@xxxxxxx.mlab.com:xxxxxx/xxxxxx";

mongoose.Promise = global.Promise;
mongoose.connect(db, function(err) {
    if(err) {
        console.log('Connection error');
    }
});

router.get('/posts', function(req, res) {
    console.log('Requesting posts');
    post.find({})
        .exec(function(err, posts) {
            if (err) {
                console.log('Error getting the posts');
            } else {
                res.json(posts);
                console.log(posts);
            }
        });
});
//in order for server.js file to access the api, we have to add the foll line
module.exports = router;

2017 年 5 月 23 日

May 23, 2017

现在我也收到了弃用警告,而实际上我已经包含了 foll loc:

Now i'm also getting deprecation warning when in fact i have included the foll loc:

mongoose.Promise = global.Promise; //we add this because if we dont, you may get a warning that mongoose's default promise library is deprecated

如果我能得到有关此问题的指导,我将不胜感激.谢谢

I'd appreciate if i can get some guidance with this issue. Thanks

推荐答案

添加我的答案,因为其他人没有给出清晰的图片.

Adding my answer as the others don't give a clear picture.

由于您将 mongoose 用作全局承诺 mongoose.Promise = global.Promise,因此您必须使用 .then().catch()

Since you're making mongoose available as a global promise mongoose.Promise = global.Promise you'll have to handle the promise using .then() and .catch()

方法如下:

...
mongoose.Promise = global.Promise;
mongoose.connect(db)
  .then(res => console.log("Connected to DB"))
  .catch(err => console.log(err))
...

这篇关于如何解决猫鼬中的 UnhandledPromiseRejectionWarning?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆