DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Node.js and MongoDB, A Beginner’s Approach

Node.js and MongoDB, A Beginner’s Approach

Kristiono Setyadi user avatar by
Kristiono Setyadi
·
Apr. 25, 12 · Interview
Like (0)
Save
Tweet
Share
17.38K Views

Join the DZone community and get the full member experience.

Join For Free

This is not a book and I didn’t try to sell a book to you.

The term “A Beginner’s Approach” reflects my own tribulations trying to connect Nodejs to MongoDB as a beginner in these technologies. There are lots of libraries available to use when connecting Node.js to MongoDB. If you were trying to get your feet wet, and that’s what I’ve been doing, you probably want to try this approach. I can’t promise anything but at least, you will not get a headache.

First, read about Nodejs. After that, MongoDB. If you’re already familiar with it, skip it and install both on your system. There maybe vary depending on your system. If you use Mac and Homebrew (or MacPorts), you’re lucky. Just do this:

$ brew install node

to install Nodejs, and:

$ brew install mongodb

or

$ sudo port install mongodb

to install MongoDB.

Next, you should familiar on how Nodejs and MongoDB works. Playing a whole day is probably enough to grasp the idea if you are a Javascript-ers and you are familiar with web server programming. If you aren’t, you should have no problem learning them in a short time, probably a week or two, if you willing to.

Okay, here’s the fun part. Oh wait, we need to install one more additional driver to connect from Nodejs to MongoDB. I’ve picked node-mongodb-native by christkv and I recommend you to install it too. It’s easy.

$ npm install mongodb

Now we’re ready to go.

To prepare a connection to MongoDB, you can create variables that define the database and its server, like this one:

var Db = require('mongodb').Db;
var Server = require('mongodb').Server;

and then instantiate a database client:

var client = new Db('test', new Server('127.0.0.1', 27017, {}));

'test' is your database name. This is usually available from the first time you install MongoDB. The IP address is obvious. 27017 refers to the specific port of your database.

Next, you may want to define the action for insert, remove, update, and show the data. Here’s mine.

var insertData = function(err, collection) {
    collection.insert({name: "Kristiono Setyadi"});
    collection.insert({name: "Meghan Gill"});
    collection.insert({name: "Spiderman"});
    // you can add as many object as you want into the database
}

var removeData = function(err, collection) {
    collection.remove({name: "Spiderman"});
}

var updateData = function(err, collection) {
    collection.update({name: "Kristiono Setyadi"}, {name: "Kristiono Setyadi", sex: "Male"});
}

var listAllData = function(err, collection) {
    collection.find().toArray(function(err, results) {
        console.log(results);
    });
}

Now, the final step is to open the connection and do what you want with your already-defined action above.

client.open(function(err, pClient) {
    client.collection('test_insert', insertData);
    client.collection('test_insert', removeData);
    // etc.
}

You’ve noticed that there is a 'test_insert' parameter. 'test_insert' is your collection name (you can go with different name though). You can think a collection just like a table in SQL database, but without a relation (that’s why we often call it NoSQL because it has no relationship like SQL does).

These codes are far from perfect. I simplify it for the sake of, surprise surprise, simplicity and easy to understand. I uploaded the source code to my Github too. So if you want to try a little bit further, you can do whatever you like, based on my code, to explore more about Nodejs and MongoDB.

Any comments or questions are definitely welcome.

Update: I forgot to mention that for the sake of simplicity, I’m not including a callback following some operations above. Christkv, the author of the native driver I’ve used here, has give us a clue on his comment below so I just want to say that if you want (and ready) to know more about callback, please read here

Node.js MongoDB

Published at DZone with permission of Kristiono Setyadi. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Host Hack Attempt Detection Using ELK
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • Assessment of Scalability Constraints (and Solutions)
  • Chaos Engineering Tutorial: Comprehensive Guide With Best Practices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: