Search code examples
mongodbaws-lambdaalexa-skills-kit

Not being able to connect to MongoDB from AWS Lambda


I am trying to build an alexa skill that connects to mlab when requested. I have put multiple console.log() messages in my code and observed that the console inside

db.once('open', function callback() { console.log('a');}) is not getting executed.

When looking up the CloudWatch logs, i get this message:

REPORT RequestId: 1b57c8f8-61b6-11e8-9038-5fc7c131d222 Duration: 40.54 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 51 MB

I have used the standard connection statements as prescribed by mongoose:

"use strict";
var Alexa = require("alexa-sdk");
const mongoose = require("mongoose");
var handlers = {

'LanguageIntent': function () {
  let uri = 'mongodb://my_uri';
  mongoose.connect(uri);
  let speechOutput;
  let db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));

  db.once('open', function callback() {
    console.log("I AM HERE");
  });
  console.log("Outside");
 }
}
exports.handler = function(event, context, callback){
  var alexa = Alexa.handler(event, context);
  alexa.registerHandlers(handlers);
  alexa.execute();
};

As far as I understand, The request is NOT getting timed out, and there must be some other problem that I can't understand. The cloudwatch log doesn't show "I AM HERE". But "Outside" gets recorded in the logs. This makes me think that there must be some problem while establishing a connection.

Any help in this regard would be highly appreciated!


Solution

  • After a week of debugging sprints, I found the answer to my problem. My code was of the format:

    "use strict";
    var Alexa = require("alexa-sdk");
    const mongoose = require("mongoose");
    var handlers = {
    'LanguageIntent': function () {
      let uri = 'mongodb://my_uri';
      mongoose.connect(uri);
      let speechOutput;
      let db = mongoose.connection;
      db.on('error', console.error.bind(console, 'connection error:'));
    
      db.once('open', function callback() {
       console.log("I AM HERE");
      });
      console.log("Outside");
      this.response.speak("HI");
      this.emit(':responseReady');
    }
    exports.handler = function(event, context, callback){
      var alexa = Alexa.handler(event, context);
      alexa.registerHandlers(handlers);
      alexa.execute();
    };
    

    I noticed that the moment I moved my reponse.speak code INSIDE the db.once function, it started working seamlessly. Therefore, the correct way to structure the code is:

    db.once('open', function callback() {
       this.response.speak("HI");
       this.emit(':responseReady');
    });