How to resolve UnhandledPromiseRejectionWarning in mongoose?

前端 未结 4 2079
野趣味
野趣味 2020-12-19 08:41

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

相关标签:
4条回答
  • 2020-12-19 08:43

    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))
    ...
    
    0 讨论(0)
  • 2020-12-19 08:46

    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);
    });
    
    0 讨论(0)
  • 2020-12-19 08:47

    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);
            }
        })
    });
    
    0 讨论(0)
  • 2020-12-19 08:53

    workaround => use the event listener

       mongoose.connect('mongodb://localhost:27017/yourDB', {
          useNewUrlParser: true
        });
        mongoose.connection.on('error', err => {
          throw 'failed connect to MongoDB';
        });
    
    0 讨论(0)
提交回复
热议问题