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

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

问题描述

我正试图使用​​猫鼬来获取数据.

I'm trying to fetch data using mongoose.

所以每次我要从api中获取帖子时-localhost:3000/api/posts-我会收到无法解密的foll错误.

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.

(节点:12100)UnhandledPromiseRejectionWarning:未处理的诺言 拒绝(r
弹出ID:1):[MongoError:连接ETIMEDOUT xxxx]

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

foll是我在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

推荐答案

您需要为代码提供一些拒绝处理程序,例如:

You need some reject handler for your code, for example:

 router.get('/posts', function(req, res) {
    console.log('Requesting posts');
    post.find({})
        .exec()
        .then(function(posts) {
            res.json(posts);
            console.log(posts);
        })
        .catch(function(error){
            console.log('Error getting the posts');
        });
});

或者不使用promise链接,而只使用回调函数:

Or don't use promise chaining use just callback function:

router.get('/posts', function(req, res) {
    console.log('Requesting posts');
    post.find({}, function(err, posts){
        if (err) {
            console.log('Error getting the posts');
        } else {
            res.json(posts);
            console.log(posts);
        }
    })
});

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

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