- Home
- >
- Ecommerce Development
- >
- Update Auto Backup MongoDB Database with NodeJS on server
Auto Backup MongoDB Database with NodeJS on server is an article sent to you by the InApps editorial team. Hope readers will have more useful knowledge at www.inapps.net
You are viewing the article: Auto Backup MongoDB Database with NodeJS on server
This tutorial describes the process for Auto Backup MongoDB Database with NodeJS on server.
Prerequisites:
- Fs and lodash npm modules are installed.
- Make sure that your mongodb is protected with username and password, if not than follow steps from below link.
Key Summary
- Overview: The article explains how to implement an automated backup system for MongoDB databases using Node.js, ensuring data safety and recovery on servers.
- Key Features:
- Automation Script: Uses Node.js to schedule and automate MongoDB backups with tools like mongodump.
- Scheduling: Integrates with libraries like node-cron to run backups at specified intervals (e.g., daily, weekly).
- Storage Options: Saves backups to local servers, cloud storage (e.g., AWS S3, Google Cloud Storage), or other remote locations.
- Compression: Compresses backup files to save storage space using tools like tar or zip.
- Error Handling: Implements logging and notifications (e.g., via email or Slack) to alert administrators of backup failures.
- Implementation Steps:
- Install Node.js, MongoDB tools, and dependencies (e.g., node-cron, aws-sdk).
- Write a Node.js script to execute mongodump for database exports.
- Configure cron jobs for scheduling and cloud storage for saving backups.
- Add error handling and logging for reliability.
- Use Cases:
- Ensuring data recovery for web applications using MongoDB.
- Automating backups for production environments in startups or enterprises.
- Maintaining compliance with data retention policies in regulated industries.
- Benefits:
- Reduces risk of data loss with regular, automated backups.
- Saves time and effort compared to manual backup processes.
- Flexible storage options support scalability and accessibility.
- Challenges:
- Requires secure handling of credentials for MongoDB and cloud storage.
- Managing large databases may increase backup time and storage costs.
- Needs monitoring to ensure consistent backup success.
- Conclusion: Automating MongoDB backups with Node.js provides a reliable, scalable solution for data protection, streamlining operations and ensuring business continuity with minimal manual effort.
Step 1
Create a js file in your project folder called mongodb_backup.js and add below code.
Replace variables < databaseUsername >, < databasePassword >, < databaseName > , < serverPath > with the values of your database.
var fs = require('fs'); var _ = require('lodash'); var exec = require('child_process').exec; var dbOptions = { user: '<databaseUsername>', pass: '<databasePassword>', host: 'localhost', port: 27017, database: '<databaseName>', autoBackup: true, removeOldBackup: true, keepLastDaysBackup: 2, autoBackupPath: '<serverPath>' // i.e. /var/database-backup/ }; /* return date object */ exports.stringToDate = function (dateString) { return new Date(dateString); } /* return if variable is empty or not. */ export.empty = function(mixedVar) { var undef, key, i, len; var emptyValues = [undef, null, false, 0, '', '0']; for (i = 0, len = emptyValues.length; i < len; i++) { if (mixedVar === emptyValues[i]) { return true; } } if (typeof mixedVar === 'object') { for (key in mixedVar) { return false; } return true; } return false; }; // Auto backup script dbAutoBackUp: function () { // check for auto backup is enabled or disabled if (dbOptions.autoBackup == true) { var date = new Date(); var beforeDate, oldBackupDir, oldBackupPath; currentDate = this.stringToDate(date); // Current date var newBackupDir = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate(); var newBackupPath = dbOptions.autoBackupPath + 'mongodump-' + newBackupDir; // New backup path for current backup process // check for remove old backup after keeping # of days given in configuration if (dbOptions.removeOldBackup == true) { beforeDate = _.clone(currentDate); beforeDate.setDate(beforeDate.getDate() - dbOptions.keepLastDaysBackup); // Substract number of days to keep backup and remove old backup oldBackupDir = beforeDate.getFullYear() + '-' + (beforeDate.getMonth() + 1) + '-' + beforeDate.getDate(); oldBackupPath = dbOptions.autoBackupPath + 'mongodump-' + oldBackupDir; // old backup(after keeping # of days) } var cmd = 'mongodump --host ' + dbOptions.host + ' --port ' + dbOptions.port + ' --db ' + dbOptions.database + ' --username ' + dbOptions.user + ' --password ' + dbOptions.pass + ' --out ' + newBackupPath; // Command for mongodb dump process exec(cmd, function (error, stdout, stderr) { if (this.empty(error)) { // check for remove old backup after keeping # of days given in configuration if (dbOptions.removeOldBackup == true) { if (fs.existsSync(oldBackupPath)) { exec("rm -rf " + oldBackupPath, function (err) { }); } } } }); } }
Step 2
To create cron install cron module from NPM package manager https://www.npmjs.com/package/cron using below command
npm install cron –save
Add below code into your server.js / main.js / index.js
global.CronJob = require(‘Your path to cron.js file’);
Now create cron.js file in your project and paste below code in it.
var CronJob = require('cron').CronJob; var Cron = require('./mongodb_backup.js'); new CronJob('0 0 0 * * *', function() { Cron.dbAutoBackUp(); }, null, true, 'America/New_York');
Any questions or problems, please, ask us and We’ll happy to help you.
Follow this to make sure you’ve got Auto Backup MongoDB Database with NodeJS on server. Save and share with those around you these extras.
To learn more about ECOMMERCE DEVELOPMENT
Contact us:
www.inapps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.