Hey there! As a fellow technology enthusiast, I know how exciting it can be to learn new skills that let you build powerful web apps. In this comprehensive guide, I‘ll walk you through everything you need to know to get started with MongoDB and NodeJS.
These two technologies are some of my personal favorites for web development. I‘ve used them to build all kinds of apps – from simple CRUD APIs to large scale web apps handling millions of users. Based on my experience, I‘ll provide unique insights so you can become an expert in no time!
Why MongoDB and NodeJS?
Before we dive in, let‘s look at why MongoDB and NodeJS are great technologies to learn in 2022:
MongoDB
- Document model is flexible and maps nicely to JavaScript objects
- Horizontally scalable using sharding
- Replication provides high availability
- Fast query performance compared to relational databases
- Expressive query language that is easy to learn
According to Db-Engines rankings, MongoDB is the #1 most popular NoSQL database right now. Major companies like Google, Facebook and eBay all use MongoDB to power their web apps.
NodeJS
- Uses JavaScript for front-end and back-end code
- Asynchronous, event-driven architecture
- Very fast due to Google‘s V8 engine
- Easy to scale across multiple servers
- Huge ecosystem of open source packages
NodeJS has exploded in popularity over the last few years. The number of NodeJS developers has tripled between 2017 to 2022. Top companies like Netflix, Uber and Paypal all use NodeJS extensively in production.
By learning MongoDB and NodeJS together, you get the best of both worlds – a document based NoSQL database that integrates cleanly with NodeJS. This powerful combo allows you to build fast, scalable web apps using just one programming language.
Excited? Let‘s dive in and install each component.
Installing MongoDB
MongoDB provides installers for all major operating systems on its official website. Here‘s how to install it on Mac, Windows and Linux.
On Mac
The easiest way to install MongoDB on Mac is using Homebrew:
brew install mongodb
After installation, you can start the MongoDB server daemon by running:
mongod
By default, it will store data in /usr/local/var/mongodb
. Make sure this directory exists!
To configure MongoDB to start automatically when your system boots up, run:
brew services start mongodb-community
And that‘s it! MongoDB is now ready to use on your Mac.
On Windows
To install MongoDB on Windows, download the MSI installer from:
https://www.mongodb.com/try/download/community
Run the installer and follow the setup wizard. I recommend installing MongoDB Compass along with it, which provides a user friendly GUI to view and manipulate your MongoDB data.
Once installed, create a data directory for MongoDB, for example C:\data\db
. Open Command Prompt as Administrator and run the mongod
executable:
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
This will launch mongod
, the primary daemon process that handles data requests and manages data access.
To run MongoDB automatically on startup, run the following in PowerShell as Administrator:
& $env:ProgramFiles\MongoDB\Server\4.2\bin\Install-WindowsService.ps1
This installs MongoDB as a Windows service. You can now control the service with the command:
net start MongoDB
And that covers installation on Windows!
On Linux
The installation process on Linux depends on your distro.
For Debian/Ubuntu, run:
sudo apt-get install mongodb
For RHEL/CentOS, run:
sudo yum install mongodb-org
This will install the latest MongoDB packages from the official repositories.
After installing, you can start the MongoDB service with:
sudo systemctl start mongod
On Ubuntu, MongoDB will automatically start on reboot. For other distros like CentOS, run:
sudo systemctl enable mongod
And that‘s it! MongoDB is ready to use on Linux.
Now that we have MongoDB installed, let‘s look at getting NodeJS up and running.
Installing NodeJS
NodeJS provides simple installers or packages for all major platforms on their official website.
On Mac or Windows
Download the installer for Mac or Windows from the NodeJS website and run through the installation wizard.
Alternatively, for Mac users, you can use Homebrew to install NodeJS:
brew install node
Once installed, verify NodeJS is working properly:
node -v
# v10.15.3
npm -v
# 6.4.1
This prints the Node and NPM versions you have installed.
On Linux
The easiest way to install NodeJS on Linux is using your distro‘s package manager:
# Ubuntu/Debian
sudo apt install nodejs npm
# RHEL/CentOS
sudo yum install nodejs npm
Verify the versions:
node -v
npm -v
And that‘s it! NodeJS is installed and ready to use.
Now that our environment is setup properly, let‘s write a simple NodeJS script to connect and use MongoDB.
Connecting to MongoDB from NodeJS
Connecting to MongoDB from Node is straightforward using the MongoDB NodeJS driver.
First, initialize a NodeJS project:
mkdir my-project
cd my-project
npm init -y
This will create a package.json
with default values to start a Node app.
Next, install the MongoDB driver:
npm install mongodb
Now create a script called app.js
and require the MongoDB driver:
// app.js
const MongoClient = require(‘mongodb‘).MongoClient;
We can use MongoClient
to connect to our local MongoDB instance:
const url = ‘mongodb://localhost:27017‘;
MongoClient.connect(url, {
useNewUrlParser: true
}, (err, client) => {
if (err) {
return console.log(‘Unable to connect to server‘);
}
// Connection successful
const db = client.db(‘my-database‘);
// Rest of app code goes here
client.close();
});
This connects to MongoDB on port 27017, which is the default. We also specify the database name we want to use, in this case my-database
.
If there are no errors, we get a reference to the db
object that lets us execute CRUD operations on the database.
And that‘s it! Our NodeJS app is now connected with MongoDB.
Let‘s look at how we can start integrating MongoDB with a simple web app.
Building a Simple CRUD Web App with Express and MongoDB
Now that we know how to connect MongoDB to a NodeJS app, let‘s build a simple CRUD web application using the popular Express framework.
Our app will have APIs to:
- Create a user
- Get all users
- Get a single user
- Update a user
- Delete a user
First, install Express in your NodeJS project:
npm install express
Now let‘s define our Express app:
// app.js
const express = require(‘express‘);
const app = express();
app.use(express.json());
// Rest of app code...
app.listen(3000, () => {
console.log(‘App listening on port 3000‘);
});
This creates an Express app that listens on port 3000 for incoming requests. We also configure it to parse JSON request bodies.
Next, let‘s define APIs to handle all CRUD operations:
// CREATE
app.post(‘/users‘, async (req, res) => {
const user = req.body;
const result = await db.collection(‘users‘).insertOne(user);
res.send(result);
});
// READ
app.get(‘/users‘, async (req, res) => {
const users = await db.collection(‘users‘).find().toArray();
res.send(users);
});
// READ ONE
app.get(‘/users/:id‘, async (req, res) => {
const userId = req.params.id;
const user = await db.collection(‘users‘).findOne({ _id: userId });
res.send(user);
});
// UPDATE
app.put(‘/users/:id‘, async (req, res) => {
const userId = req.params.id;
const user = req.body;
const result = await db.collection(‘users‘).updateOne(
{ _id: userId },
{ $set: user }
);
res.send(result);
});
// DELETE
app.delete(‘/users/:id‘, async (req, res) => {
const userId = req.params.id;
const result = await db.collection(‘users‘).deleteOne({ _id: userId });
res.send(result);
});
These routes handle all the CRUD logic using MongoDB driver‘s methods like insertOne
, find
etc.
To test this out, start your Express server:
node app.js
Open Postman and make requests to these endpoints. For example, to create a user:
POST /users
{
"name": "John",
"age": 30
}
This will save the user to MongoDB and return the result. Try out the other APIs like GET, PUT and DELETE.
And that‘s it! In just a few lines of code, we have a fully functional CRUD API with MongoDB integration.
While our app works, it can benefit from some improvements:
- Input validation using Mongoose schemas
- Authentication and authorization
- Error handling middleware
- Configuration for deployment
Still, we covered the core goal – connecting MongoDB to a Node+Express app and performing CRUD operations. With this foundation, you can build out the full-fledged backend for any web or mobile app.
Best Practices for NodeJS + MongoDB
Now that you know how to use MongoDB in NodeJS apps, let‘s go over some best practices to follow:
-
Use Mongoose schemas – Defining schemas helps validate and sanitize data before inserting into MongoDB.
-
Handle errors properly – Make sure to handle all errors from the MongoDB driver to avoid crashes.
-
Async/await for cleaner code – Managing Promises can get messy. Use async/await for cleaner code.
-
Use environment variables – Store sensitive credentials like Mongo URL in environment variables.
-
Add logging – Use a logger like Winston to get insights into errors or performance issues.
-
Use connection pooling– Create a single MongoDB connection instance and reuse it across your app.
-
Create indexes judiciously – Add indexes on frequently queried fields to improve performance.
-
Use multiple databases if needed – Split data across databases if it improves organization.
Following these best practices will lead to stable, production-ready apps with MongoDB and NodeJS.
Example Projects to Learn From
An easy way to improve your NodeJS and MongoDB skills is to analyze real world project code.
Here are some great open source repos to learn from:
-
REST API – Full-fledged REST API with MongoDB, Mongoose & Passport auth
-
RealWorld spec – Backend implementation of Medium.com clone
-
Todo API – Simple REST API managing ToDos
-
Chat app – Messaging web app with React and Socket.io
Browse through these repos to get ideas for your own projects. Analyzing real code is a great way to reinforce your learning.
Key Takeaways
Let‘s summarize the key points about MongoDB and NodeJS:
- MongoDB is a popular document-based NoSQL database that scales well and provides expressive querying
- NodeJS is a JavaScript runtime that lets you build fast network apps using async I/O
- The MongoDB NodeJS driver makes it easy to integrate MongoDB with Node
- You can perform CRUD operations seamlessly using the driver methods
- Express framework allows quickly building REST APIs and web apps with NodeJS
- Make sure to follow best practices around input validation, error handling etc.
- Analyzing open source projects helps improve your coding skills
With MongoDB‘s flexible documents and NodeJS‘s asynchronous handling, you have all the tools needed to build production-ready apps.
Next Steps
Congratulations, you now have the foundations to start building full stack apps with MongoDB and NodeJS!
Here are some ideas to improve your skills:
- Build a simple CRUD app end-to-end
- Explore other parts of MongoDB like aggregation
- Implement user authentication and sessions
- Containerize your apps with Docker for easy deployment
- Optimize performance using indexing and caching
- Migrate an existing SQL-based app to use MongoDB
- Sign up on MongoDB Atlas to easily build clusters
- Check out mongoosepopulation.com for loads of example MongoDB schemas
Thanks for reading this guide all the way through! Let me know if you have any other questions.
Happy coding!