User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @snebiker: #PlayGameLieschtel - brilliant event by Kantonsbibliothek Baselland #KBL to get kids into libraries, including family #gamede…
About 2 days, 13 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Only a handful tickets left for @PyConDE in Karlsruhe (October 24-28, 2018) - The schedule is now available at… https://t.co/Og4fp3DsoA
About 5 days, 6 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

IAMCP & @swissmade_sw Augmented Reality event just started https://t.co/bdREI6lJM4 #ar #AugmentedReality #Basel… https://t.co/9KpsdU3fvM
About 6 days, 12 hours ago by: Martin Christen (@MartinChristen)
node:tutorial08

Node.js Tutorials - Part 0

Node.js Tutorial 8

Getting started with MongoDB and node.js

MongoDB (from “humongous”) is an open-source document “NoSQL” database. MongoDB is written in C++ and is highly scaleable. More info at: http://www.mongodb.org/

The node.js integration for MongoDB is available at http://mongodb.github.io/node-mongodb-native/.

In this first tutorial about node.js + MongoDB we're connecting to the database, creating a new collection, and finding entries in the collection.

Installation of MongoDB

First you need a mongodb installation. MongoDB can be downloaded from http://www.mongodb.org/downloads. Make sure to use a 64-bit version if possible.

Linux

On various linux distributions MongoDB can be retrieved as a package. In Ubuntu, for example, this is pretty easy:

sudo apt-get install mongodb

Windows

For installation under Windows you can get instructions at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/. Make sure it is extracted under C:\mongodb. Start MongoDB by entering:

C:\mongodb\bin\mongod.exe

you can also install mongodb as a service using:

C:\mongodb\bin\mongod.exe --install --logpath c:\mongodb\log.txt
net start MongoDB

You can now open http://localhost:28017/ in your browser to test if everything works propery.

Installing MongoDB node.js Driver

npm install mongodb

Creating a new database

In MongoDB you don't create a database. You just access a collection. If it doesn't exist yet, it will be created as soon as you insert objects.

First we need the MongoClient object:

var MongoClient = require('mongodb').MongoClient

Then we connect to the MongoDB:

MongoClient.connect('mongodb://localhost:27017', function(err, db) {

      // code when connected

});

Now we get the collection, let me call it 'tutorial08'. If this “database” doesn't exist, it doesn't matter, it will be created as soon as you insert data:

   var collection = db.collection('tutorial08');
</sxh


Finding an existing object in the db can be done using various find commands. I'm using "findOne". This only gives back the first object found, useful if you have primary keys.

<sxh js; gutter: false;>
   var key = "myKey";
   collection.findOne({"key": key}, function(err, res) {
       // code here is called as soon as findOne finished
   }

Inserting a new object is done using “collection.insert”:

var myObject = {
            "key": key,
            "value": 1234 };
collection.insert(myObject, function(err, res) {
   // code called as soon as object is inserted (or error)
}
          
          
Don't forget to close the connection as soon as you're finished:
<sxh js; gutter: false;>
db.close();

The full source Code

var MongoClient = require('mongodb').MongoClient

MongoClient.connect('mongodb://localhost:27017', function(err, db) {

   if(err) throw err;

   var collection = db.collection('tutorial08');

   var key = "myKey";

   collection.findOne({"key": key}, function(err, res) {

      if(err) throw err;

      if (res)
      {
         console.log("result:", res);
         db.close();
      }
      else
      {
         // creating new entry
         console.log("creating new entry!");

         // create an object:
         var myObject = {
            "key": key,
            "value": 1234 };

         collection.insert(myObject, function(err, res) {
            // close connection:
            db.close();
         });
      }
   });
});


node/tutorial08.txt · Last modified: 2013/09/16 22:05 by mchristen