如何在mongoose中解决UnhandledPromiseRejectionWarning?

时间:2017-05-22 07:32:55

标签: node.js mongodb mongoose

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

因此每次我都要从api-localhost:3000 / api / posts获取帖子 - 我得到了foll错误,我无法解密。

  

(node:12100)UnhandledPromiseRejectionWarning:未处理的承诺   拒绝(r
  弹射ID:1):[MongoError:连接ETIMEDOUT xxxx]

这是我在api.js文件中的代码。如果你能提供关于我在哪里出错的指导,我将不胜感激。

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日

现在我也得到了弃用警告,实际上我已经包含了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

如果我能就此问题获得一些指导,我将不胜感激。感谢

4 个答案:

答案 0 :(得分:2)

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

 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 chaining只使用回调函数:

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

答案 1 :(得分:0)

处理它的正确方法是添加一个catch子句。

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI).catch(function (reason) {
    console.log('Unable to connect to the mongodb instance. Error: ', reason);
});

答案 2 :(得分:0)

添加我的答案,因为其他人不能给出清晰的图片。

由于您将function aaa(string){ var aa = string.split('=')[0], bb = string.split('=')[1]; function setValue(object, path, value) { var way = path.split('.'), last = way.pop(); way.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value; return object; } var object = JSON.stringify(setValue({}, aa, bb)); console.log(object); } 作为全球承诺[{1}}提供,因此您必须使用mongoosemongoose.Promise = global.Promise

以下是:

.then()

答案 3 :(得分:0)

解决方法=>使用事件监听器

   mongoose.connect('mongodb://localhost:27017/yourDB', {
      useNewUrlParser: true
    });
    mongoose.connection.on('error', err => {
      throw 'failed connect to MongoDB';
    });
相关问题