Auto Backup MongoDB Database with NodeJS on server

Jan 13th, 2017

Auto Backup MongoDB Database with NodeJS on server

Table of Contents

Share

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.

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.

Comments are closed.

Let's Discuss Your Project

Get free consultation and let us know your project idea to turn
it into an amazing digital product.

Let’s talk

NEWS & BLOG

Related Blogs

How Long Does It Take to Develop a Mobile App?

AI Oct 21st, 2024

How Long Does It Take to Develop a Mobile App?...

Read more
Digital Transformations Re-Engineering for Success for the 21st Century

Big Data Apr 25th, 2017

Digital Transformations Re-Engineering for Success for ...

Read more
8 Simple steps to install MongoDB with authentication on EC2 AMI Linux

Big Data Jan 10th, 2017

8 Simple steps to install MongoDB with authentication o...

Read more

INQUIRY

Let's get in touch

UNITED STATES

4411 Suwanee Dam road,
Bld. 300 Ste. 350
Suwanee GA, 30024

Sales: +1 (415) 230 0051

UNITED KINGDOM

Kemp House 160 City Road, London,United Kingdom EC1V 2NX

Sales: +44 7404 607567

INDIA

2nd Floor, Sun Avenue One, Bhudarpura, Ayojan Nagar, Nr. Shyamal Cross Road, Ahmedabad, Gujarat-380006

Sales: +91 635-261-6164

For Project Inquiries

emailsales@solutionanalysts.com emailcareer@solutionanalysts.com skypebiz.solutionanalysts