Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

node.js - How to resolve UnhandledPromiseRejectionWarning in mongoose?

I'm trying to fetch data using mongoose.

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: Unhandled promise rejection (r
ejection id: 1): [MongoError: connect ETIMEDOUT xxxx]

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;

May 23, 2017

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Here's how:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...