Learning Node.js MongoDB
- Part 1: Terminology and Comparison with SQL
- Part 2: Connecting and Creating
- Part 3: Reading
- Part 4: Updating
- Part 5: Deleting
MongoDB is a popular NoSQL document-oriented database system. The Node.js driver allows for connecting to an existing MongoDB installation or system.
Installation
The MongoDB drive for Node.js can be installed through using NPM.
npm install mongodb --save
Connecting
Assuming the MongoDB driver is loaded, connecting to a MongoDB system is based on a MongoClient object and a connection URL.
(Assuming MongoDB is running on localhost, the default port is 27017.)
For MongoDB, if a database does not exist, it will be created upon first usage.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
db.close();
});
The connect() function accepts two arguments, the connection URL and a callback Promise function upon success. The two arguments passed to the callback function will be first, an error value, and second, an object containing the connection MongoClient object, if successful.
Using the db() function, a database can be selected (or created, if it does not already exist upon first access) that shares the same connection information.
Creating Collections
Using the db.db() function (or based on the connection URL), a collection can be created through using the createCollection() function through supplying a new collection name.
Like with databases, collection names will be initially reserved upon first access. However, they will not truly be created until they have documents.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("example");
dbo.createCollection("users", function(err, res) {
if (err) throw err;
db.close();
});
});
Creating Documents
Documents are created within an existing collection using the insertOne() or insertMany() functions. Object literals (or an array of them) passed to either functions will add those documents to the existing collection.
The use of either function automatically adds a primary key during the insertion, guaranteeing unique data per document.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("example");
var myobj = { name: "Dan Cox", blogPost: "2" };
dbo.collection("users").insertOne(myobj, function(err, res) {
if (err) throw err;
db.close();
});
});