MongoDB with Node.js
MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. It works on the concept of collections and documents. On the other hand, Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser. MongoDB and Node.js are often used together because of their shared use of JavaScript and its object notation, JSON.
In this tutorial, we will guide you through setting up a MongoDB database and interacting with it using Node.js.
Setting Up the Environment
Before we begin, you need to have Node.js installed on your machine. You can download it from the official Node.js website.
Also, you need to have a MongoDB server running. You can download MongoDB from the official MongoDB website.
Once you have these installed, create a new folder on your computer and initialize a new Node.js application by running npm init
.
Connecting Node.js to MongoDB
To connect our Node.js application to a MongoDB database, we will use an NPM package called mongodb
.
npm install mongodb
Then, in your main application file, require the mongodb
package and use it to connect to your database.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
This code connects to a MongoDB server running on localhost
on port 27017
and tries to connect to a database named mydb
.
Working with Data
Creating a Collection
In MongoDB, a collection is a grouping of MongoDB Documents and is the equivalent of an RDBMS table. You can create a collection using the createCollection
method.
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
Inserting Data
You can insert data into a MongoDB collection using insertOne
or insertMany
methods.
const myobj = { name: "Company Inc", address: "Highway 37" };
db.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
Querying Data
You can retrieve data using the find
method. The find
method returns all occurrences in the selection. To select data from a collection in MongoDB, we can use the findOne
method.
db.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
Updating Data
You can update a record, or document as it is called in MongoDB, by using the updateOne
method.
const myquery = { address: "Valley 345" };
const newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
db.collection("customers").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
Deleting Data
You can delete data from the MongoDB database by using the deleteOne
method.
const myquery = { address: 'Mountain 21' };
db.collection("customers").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
Conclusion
In this tutorial, we have learned how to connect a Node.js application to a MongoDB database, create a collection, insert data, query data, update data, and delete data. You can now start building applications with Node.js and MongoDB.
Remember that MongoDB is schema-less, meaning it does not require a predefined schema before you can add data to a collection. You can add any type of data you want without any restrictions.
Happy coding!