8

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

Nosail
  • 465
  • 2
  • 7
  • 19

4 Answers4

5

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))
...
m-ketan
  • 1,258
  • 2
  • 17
  • 23
3

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

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);
        }
    })
});
Sergaros
  • 821
  • 1
  • 5
  • 14
  • Thanks Sergaros; i tried both the alternatives, but i'm getting the same error. – Nosail May 22 '17 at 09:35
  • UnhandledPromiseRejectionWarning - it's mean somewere in your code you use promises without reject handler so you need find it place and add reject handler – Sergaros May 22 '17 at 09:41
  • i'm not using any promises in the api.js code that i have shared. – Nosail May 22 '17 at 09:50
  • post.find({}).exec().then(... chaining like this called promises – Sergaros May 22 '17 at 09:53
  • And one more question, why you use 'mongoose.Promise = global.Promise;' not just 'mongoose.Promise = Promise;' ? – Sergaros May 22 '17 at 09:54
  • 1
    i use it coz of the guidance in the foll: https://github.com/Automattic/mongoose/issues/4742 – Nosail May 22 '17 at 09:58
  • yes; but my original code does not have any promises... so i was just wondering the reason for this persistent error. – Nosail May 22 '17 at 10:45
2

The proper way to handle it is to add a catch clause.

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI).catch(function (reason) {
    console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
Andrey Petrov
  • 2,291
  • 2
  • 15
  • 12
1

workaround => use the event listener

   mongoose.connect('mongodb://localhost:27017/yourDB', {
      useNewUrlParser: true
    });
    mongoose.connection.on('error', err => {
      throw 'failed connect to MongoDB';
    });
Polliny
  • 89
  • 1
  • 4