Learn How to Set Up Automated Backups and Database Restores for Node.js Apps Using Cron and MongoDB Atlas
Keeping your application’s data safe should never be an afterthought — it’s a vital part of any production-grade deployment. For teams running Node.js apps with MongoDB Atlas, automating your backup and restore processes using Cron and MongoDB tools ensures peace of mind and quick disaster recovery.
In this step-by-step guide, you’ll learn how to:
- Set up automated backups of your MongoDB Atlas database
- Create a restore process in case of data loss
- Use Node.js scripts and Cron jobs to schedule tasks
- Implement backup retention policies
Prerequisites
Before you begin, make sure you have:
- A MongoDB Atlas cluster
- Node.js v14 or above
- A Linux server or cloud VM to run cron jobs
- MongoDB Database Tools installed (
mongodump
,mongorestore
)
Step 1: Install MongoDB Tools
MongoDB’s CLI tools are used for taking backups and restoring data.
On Ubuntu/Debian:
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt update
sudo apt install -y mongodb-database-tools
This installs mongodump
and mongorestore
.
Step 2: Create a Backup Directory
sudo mkdir -p /var/backups/mongodb
sudo chmod 700 /var/backups/mongodb
This is where backup files will be stored securely.
Step 3: Write a Node.js Script to Back Up Your Database
Create a file named backup.js
:
const { exec } = require('child_process');
require('dotenv').config();
const fs = require('fs');
const uri = process.env.MONGO_URI;
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupPath = `/var/backups/mongodb/backup-${timestamp}`;
if (!uri) {
console.error('❌ Mongo URI not found.');
process.exit(1);
}
fs.mkdirSync(backupPath, { recursive: true });
const cmd = `mongodump --uri="${uri}" --out="${backupPath}"`;
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`❌ Backup failed: ${error.message}`);
return;
}
console.log(`✅ Backup completed: ${backupPath}`);
});
.env
file
MONGO_URI=mongodb+srv://username:password@cluster0.mongodb.net/yourDbName
Install dotenv
:
npm install dotenv
Step 4: Schedule Backups with Cron
Run backups automatically every day at 2 AM.
Edit the crontab:
crontab -e
Add this line:
0 2 * * * /usr/bin/node /full/path/to/backup.js >> /var/log/mongodb-backup.log 2>&1
Step 5: Automatically Delete Old Backups
To delete backups older than 7 days:
find /var/backups/mongodb/* -mtime +7 -exec rm -rf {} \;
Add to your crontab:
10 2 * * * find /var/backups/mongodb/* -mtime +7 -exec rm -rf {} \;
Step 6: Restore Data from a Backup
Create a restore script restore.js
:
const { exec } = require('child_process');
require('dotenv').config();
const uri = process.env.MONGO_URI;
const backupPath = process.argv[2];
if (!backupPath) {
console.error('❌ Please specify a backup directory.');
process.exit(1);
}
const cmd = `mongorestore --drop --uri="${uri}" "${backupPath}"`;
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`❌ Restore failed: ${error.message}`);
return;
}
console.log(`✅ Data restored from: ${backupPath}`);
});
Run it like this:
node restore.js /var/backups/mongodb/backup-2025-08-06T02-00-00
Optional Enhancements
- Cloud uploads: Use AWS CLI or GCP SDK to move backups offsite
- Encryption: Use
gpg
oropenssl
to encrypt backup folders - Slack/Email alerts: Add alerts in case of success/failure
Final Thoughts
By using Node.js, Cron, and MongoDB Atlas, you’ve created a lightweight, secure, and automated system to handle your database backups and restores. This system helps prevent data loss, improves uptime, and prepares your infrastructure for recovery at any time.
Related Guides
- Learn to configure domains, set up Nginx, and install free SSL certificates to make your Ionic blog secure and SEO-friendly.
- Build portable and scalable apps effortlessly by packaging your entire Ionic and Node.js stack into containers.
- A step-by-step tutorial to set up CI/CD pipelines for SSH deployment and Firebase Hosting using GitHub Actions.
- Easily deploy and manage your apps on DigitalOcean using PM2 and Nginx for high availability and performance.
0 Comments