Node.js MongoDB Tutorial With Examples
Mostly all modern-day web applications have some sort of data storage system at the backend. For example, if you take the case of a web shopping application, data such as the price of an item would be stored in the database.
The Node js framework can work with databases with both relational (such as Oracle and MS SQL Server) and non-relational databases (such as MongoDB). In this tutorial, we will see how we can use databases from within Node js applications.
In this tutorial, will learn
- Node.js and NoSQL Databases
- Using MongoDB and Node.js
- How to build a node express app with MongoDB to store and serve content
Node.js and NoSQL Databases
Over the years, database such as MongoDB and MySQL have become quite popular as databases for storing data. The ability of these databases to store any type of content and particularly in any type of format is what makes these databases so famous.
Node.js has the ability to work with both MySQL and MongoDB as databases. In order to use either of these databases, you need to download and use the required modules using the Node package manager.
For MySQL, the required module is called "mysql" and for using MongoDB the required module to be installed is "Mongoose."
With these modules, you can perform the following operations in Node.js
-
Manage the connection pooling – Here is where you can specify the number of MySQL database connections that should be maintained and saved by Node.js.
管理连接池 – 在这里可以指定Node.js应维护和保存的MySQL数据库连接数
-
Create and close a connection to a database. In either case, you can provide a callback function which can be called whenever the "create" and "close" connection methods are executed.
创建并关闭与数据库的连接。无论哪种情况,都可以提供一个回调函数,只要执行“创建”和“关闭”连接方法,就可以调用该函数
-
Queries can be executed to get data from respective databases to retrieve data.
可以执行查询以从相应的数据库中获取和检索数据
-
Data manipulation, such as inserting data, deleting, and updating data can also be achieved with these modules.
we will look at how we can work with MongoDB databases within Node.js.
Using MongoDB And Node.js
As discussed in the earlier topic, MongoDB is one of the most popular databases used along with Node.js.
During this chapter, we will see
How we can establish connections with a MongoDB database
我们如何与MongoDB数据库建立连接
How we can perform the normal operations of reading data from a database as well as inserting, deleting, and updating records in a MongoDB database.
我们如何执行从数据库读取数据以及在MongoDB数据库中插入,删除和更新记录的常规操作
Connect to MongoDB
Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.
Add code to connect to the server and the database myproject:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
Run your app from the command line with:
node app.js
The application should print Connected successfully to server to the console.
Insert a Document
Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
The insert command returns an object with the following fields:
- result Contains the result document from MongoDB
- ops Contains the documents inserted with added _id fields
- connection Contains the connection used to perform the insert
Add the following code to call the insertDocuments function:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
Run the updated app.js file:
node app.js
The operation returns the following output:
Connected successfully to server
Inserted 3 documents into the collection
Find All Documents
Add a query that returns all the documents.
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
This query returns all the documents in the documents collection. Add the findDocument method to the MongoClient.connect callback:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
insertDocuments(db, function() {
findDocuments(db, function() {
client.close();
});
});
});
Find Documents with a Query Filter
Add a query filter to find only documents which meet the query criteria.
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
Only the documents which match 'a' : 3
should be returned.
Update a document
The following operation updates a document in the documents collection.
const updateDocument = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Update document where a is 2, set b equal to 1
collection.updateOne({ a : 2 }
, { $set: { b : 1 } }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Updated the document with the field a equal to 2");
callback(result);
});
}
The method updates the first document where the field a is equal to 2 by adding a new field b to the document set to 1. Next, update the callback function from MongoClient.connect to include the update method.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
updateDocument(db, function() {
client.close();
});
});
});
Remove a document
Remove the document where the field a is equal to 3.
const removeDocument = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Delete document where a is 3
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}
Add the new method to the MongoClient.connect callback function.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
updateDocument(db, function() {
removeDocument(db, function() {
client.close();
});
});
});
});
Index a Collection
Indexes can improve your application's performance. The following function creates an index on the a field in the documents collection.
const indexCollection = function(db, callback) {
db.collection('documents').createIndex(
{ "a": 1 },
null,
function(err, results) {
console.log(results);
callback();
}
);
};
Add the indexCollection
method to your app:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
indexCollection(db, function() {
client.close();
});
});
});
For more detailed information, see the tutorials.
Note:
{ useUnifiedTopology: true }