Search code examples
javascriptnode.jstwitterpromise

Node UnhandledPromiseRejectionWarning when saving to MongoDb


New to node- I'm trying to save some of my tweets from Twitter API into mongo using Twit package.

I've connected to mongodb on port 27017 using mongoose, and this piece of code I've written seems to save the tweets to my db, however I seem to be getting this warning back everytime I save a document:

(node:9991) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)

Here is my code:

const Tweet = require('./app/models/tweet.model.js');
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(dbConfig.url, {
    useNewUrlParser: true
}).then(() => {
    console.log("Successfully connected to the database");
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
});

var Twit = require("twit");

var config = require("./config/twitter.config");
var T = new Twit(config);


var params = {
  screen_name: "decade3uk",
  count: 2
};

T.get("statuses/user_timeline", params, gotData);

function gotData(err, data, response) {

  var tweets = data;

  for(var i=0;i<tweets.length;i++){

    const tweet = new Tweet({
      created_at:tweets[i].created_at,
      id_str:tweets[i].id_str,
      text:tweets[i].text
    });

    tweet.save()
        .then(entry => {
          response.send(entry);
        }).catch(err => {
          response.status(500).send({
            message: err.message || "Some error occurred while creating the Tweet."
          });
        });

  }

}

What is best practice to get rid of this error?


Solution

  • Why don't you try to find where is that exception coming from and what exactly it is. You can find that by adding the following code to your server file, just to make sure you get what's causing the exception.

    process.on('unhandledRejection', (reason, promise) => {
       console.log("Reason: ",reason,"promise: ",promise);
    })