How to resolve UnhandledPromiseRejectionWarning in mongoose?

前端 未结 4 2081
野趣味
野趣味 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: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);
            }
        })
    });
    

提交回复
热议问题