Search code examples
node.jsopenwhisk

Unable to connect to MongoDB from NodeJS, deployed as action in OpenWhisk


I have the following code written a file called app.js. MongoDB is installed on 192.168.16.1, which is my laptop. When I run this using node app.js command, I get a message "connected".

 var mongoose = require('mongoose');
    var Schema = mongoose.Schema;


    var mongoose = require('mongoose');
    var MongoClient = require('mongodb').MongoClient;
// Connect to the db
    MongoClient.connect("mongodb://192.168.16.1:27017/angularcrud", function (err, db) {

     if(err) {console.log(err); }
     else {console.log('connected');}

});

\

I have an OpenWhisk environment setup on my laptop using Vagrant. If is ssh to vagrant and ping to 192.168.16.1, I get ping response, so I am sure that vagrant VM is able to reach 192.168.16.1. I have written the following code in NodeJS to create an OpenWhisk action. I have deployed it into openwhisk as a .zip file (which includes Node_modules folders also).

function entryPoint(args) {


    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var message = "Connection not SET";

    var mongoose = require('mongoose');
    var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://193.168.16.1:27017/angularcrud", function (err, db) {

     if(err) {return err;}
      else {return 'success';}



});
}

module.exports.main = entryPoint;

If I run the above code in OpenWhisk, I get a result {}. If I remove the MongoClient.Connect statement and return a simple string, then I am getting the string when I invoke the action. I am sure there is something wrong in the MongoClient.Connect, when run on OpenWhisk. But, I am really stuck, because I get no error to tell me what is going wrong.


Solution

  • The entryPoint function executes an asynchronous function to connect to the database. When executing asynchronous function calls, you need to return a Promise from the action handler. This ensures the platform will block on that asynchronous result before completing the invocation.

    function main() {
      return new Promise((resolve, reject) => {
        MongoClient.connect(URL,  (err, db) => {
          if(err) return reject(err)
          resolve({message: "success"})
        })        
      })
    }