0

So i have been looking at how to use mongodb from this tutorial: http://doduck.com/node-js-mongodb-hello-world-example/

I have installed mongodb locally within my project folder that contains my html css and js, i run npm list mongodb within the project folder and i get the mongodb version. I haven't installed it globablly, but as far as i know that is ok right?

Anyways, i tried adding the example from the tutorial to test connect to a mongodb database. I just created a function and called it as soon as my page loads:

function connectMongo(){
    alert("test1");
    var MongoClient = require('mongodb').MongoClient;
    alert("test2");
    var myCollection;
    var db = MongoClient.connect('mongodb://127.0.0.1:27017/test',          function(err, db) {
    if(err){
        throw err;
        alert("mongoerror");
    }
    alert("connected to the mongoDB !");
   // myCollection = db.collection('test_collection');
});

}

The first test alert works, but the second test does not appear. However, the rest of the code on the page still runs, so i dont think there is a syntax error. I have no idea how exactly im meant to run this example, can anyone tell me why my function is exiting after the line

var MongoClient = require('mongodb').MongoClient;

I also have mongoose installed, even though im not quite sure if im even using it in my example here

Sorry if my question is kind of vague, i have honestly no idea what im doing here

4
  • You mention mongoose, but you're not using that module. Do you have the mongodb module installed npmjs.com/package/mongodb? Commented Nov 29, 2015 at 3:54
  • yup, both mongodb and mongoose are installed within my project folder Commented Nov 29, 2015 at 3:55
  • You are using alert and say "as soon as my page loads". Is this javascript being served to a browser? Commented Nov 29, 2015 at 3:56
  • yes, i am building a web app, im just simply testing the mongodb examle before i actually incorporate it into my webpage Commented Nov 29, 2015 at 3:59

2 Answers 2

3

First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.

Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.

Prerequisite

Let's quickly review Client-Server web interactions:

  1. Server is up and running
  2. Client Requests page via browser
  3. Page shows up on the client's browser

enter image description here

Step 1

The missing step for you is (1), because the server is not up and running. This is done by typing the following on your terminal:

$ node name_of_file_here.js

If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.

Step 2

Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients. Some code needs to be added:

'use strict'; 
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

//Create a server
var server = http.createServer(function(request, response) {
    console.log("received request");  

    // use MongoClient to get relevant data 
    // var relevant_data = ...; 
    // response.write(relevant_data); 

    response.write("hey there"); 
    response.end(); 
}); 

server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

Final Note

I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.

Sign up to request clarification or add additional context in comments.

2 Comments

so the code under step 2, it seems like you are setting up the server for listening, is that correct? Is this the same as clicking on the mongod batch file that you download, since that also listens for incoming connections? If so, is it possible for me to include code in my original javascript file that can modify/retrieve records from this database?
Under Step 2, we setup an HTTP server for listening and a MongoDB client. You still need to run the MongoDB server externally (on your system) would advise to follow the steps in this link Install Tutorial. This relates to the final note in my answer
1

It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.

Create a file test.js

function connectMongo(){
  var MongoClient = require('mongodb').MongoClient;
  console.log('MongoClient is',typeof MongoClient)
  var myCollection;
  var url = 'mongodb://127.0.0.1:27017/test';
  var db = MongoClient.connect(url, function(err, db) {
    if(err){
      console.log("mongoerror", err);
      throw err;
    }
    console.log("connected to the mongoDB!");
    myCollection = db.collection('test_collection');
  });
}
connectMongo()

Then on your system, at a command or shell prompt, run

node test.js

It should print

$ node test.js
MongoClient is function
connected to the mongoDB!
^C

Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO

For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

1 Comment

ok, i tried this example and it does work, but i am confused at how im supposed to incorporate this into my own web app. I have my database set up already, but i want to be able to modify/retrieve records from this database within the javascript file for my web app. Is this something that can be done with nodejs?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.