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.
Read More:   Update What can Make Your Application Fail to Mark Presence in 2019

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’); 

Read More:   Update Top Industry Sectors that can Make the Most of On-demand Delivery Apps

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

Rate this post
As a Senior Tech Enthusiast, I bring a decade of experience to the realm of tech writing, blending deep industry knowledge with a passion for storytelling. With expertise in software development to emerging tech trends like AI and IoT—my articles not only inform but also inspire. My journey in tech writing has been marked by a commitment to accuracy, clarity, and engaging storytelling, making me a trusted voice in the tech community.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      Success. Downloading...