Juan David Ospina Juan David Ospina - 14 days ago 10
Node.js Question

MongoDB Cloud9 Connection

So, I am wondering if there is a way to connect to the mongoDB I have setup in my Cloud9 from an html. I mean, I have already connected to the db from the terminal and everything is working like a charm but I need to do some stuff inside my script in an html document and when I try calling the function which contains this code it does nothing



var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/ingesoft', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});





I have saved the same code into a "file.js" and ran it from console using node file.js and it outputs into the console log "successfully connected to the database", plus the terminal which is running mongo's connection shows me one more connection to the db. The thing is, when I try to run that code inside my script it doesn't work. Sorry for my ignorance I am new to mongo.

Any help would be much appreciated

Answer

To simplify your question, here's what's going on:

  • node file.js containing the code in your question is working
  • pasting the same code to your html file is not

So, getting to the bottom of the issue, let's ask first: what's the difference between running node file.js and putting the code in html?

  • The difference is that node ... is running on your Cloud9 workspace (let's call it the server machine).
  • Your MongoDB server is also running on that server machine
  • The mongodb npm package you installed is also present on the server machine
  • The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your server

whereas with the code on your browser:

  • The code is being run on your customer's machine
  • That machine doesn't have your Mongodb server
  • Browser's usually don't support require
  • You can do requires if you bundle code and use something like webpack or browserify. Did you perhaps do that?
  • If you did indeed package everything, was the mongodb package that you're requiring packaged?
  • Can the mongodb package be run from the client side?
  • The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your customer's machine

Basically, as you can see from the above, the two are very different.

If you want to talk to your db, a lot of people go the following route:

  • Make a server application that implements some form of REST API
  • That REST API talks to your DB
  • Your client code knows how to talk to the REST API and get the required data

That way, you only talk to your MongoDB using your server, and the client can talk to your server via the internet.

This is, of course, an oversimplification, but I hope this resolves your confusion.

Comments