Reputation: 101
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
Upvotes: 0
Views: 290
Reputation: 3832
To simplify your question, here's what's going on:
node file.js
containing the code in your question is workingSo, 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?
node ...
is running on your Cloud9 workspace (let's call it the server machine). mongodb
npm package you installed is also present on the server machine127.0.0.1
which is the localhost for your serverwhereas with the code on your browser:
require
webpack
or browserify
. Did you perhaps do that?mongodb
package that you're requiring packaged?mongodb
package be run from the client side?127.0.0.1
which is the localhost for your customer's machineBasically, 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:
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.
Upvotes: 1