Search code examples
node.jsmongodbcloud9-ide

Cloude9 workspace MongoDb connection


I am working in c9.io ide with nodejs project. In that I am trying to connect to mongodb database. I have already installed mongodb module.

In command prompt I can able to run mongodb commands like

use database db.inventory.find()

To take advantage of Mongodb in application, I have written below code in server.js file

//MongoDB
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://" + process.env.IP + ":" + process.env.PORT + "/[dbname]", function (err, db) {
    if (!err) {
        console.log("Mongo Connected.");
    } else {
        console.log("Mongo not Connectd");
    }
});

But after running Server.js file, I get output as

Mongo not Connected

I have outputed err variable -- And it prints

{ [MongoError: server 0.0.0.0:8080 sockets closed]
  name: 'MongoError',
  message: 'server 0.0.0.0:8080 sockets closed' }

Let me know what I am doing wrong?


Solution

  • Got help for Cloude 9 Support, The reply is as follows

    You should change the line that says:
    
    `MongoClient.connect("mongodb://" + process.env.IP + ":" + process.env.PORT + "/[dbname]", function (err, db){ `
    
    You are connecting to `process.env.PORT`, but that is not the port for mongodb.
    Simply use the default connection url here, it should work: 
    
    `mongodb://localhost:27017/[dbname]`
    

    changing mongodb://" + process.env.IP + ":" + process.env.PORT + "/[dbname] to mongodb://localhost:27017/[dbname] resolved the issue