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.

14 Comments

  • najlepszy sklep at 7:41 pm, March 16, 2024

    Wow, incredible weblog layout! How lengthy have you been blogging for?
    you make blogging look easy. The overall glance of your site is excellent, let alone the
    content material! You can see similar here sklep internetowy

  • who is the best finisher in the world at 7:22 pm, March 24, 2024

    Looking forward to reading more. Great blog post.Much thanks again. Keep writing.

  • dobry sklep at 8:27 pm, March 27, 2024

    Hello! Do you know if they make any plugins to help with SEO?

    I’m trying to get my blog to rank for some targeted keywords
    but I’m not seeing very good results. If you know
    of any please share. Appreciate it! You can read similar blog
    here: Sklep online

  • dobry sklep at 11:47 pm, March 27, 2024

    Good day! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.

    If you know of any please share. Appreciate it!
    You can read similar blog here: Sklep internetowy

  • vpn special at 4:53 pm, March 31, 2024

    Hi, I do think this is a great web site. I stumbledupon it 😉 I am going to return once again since I book marked it.

    Money and freedom is the greatest way to change, may you be rich and continue to guide others.

    Have a look at my web site … vpn special

  • vpn special coupon at 4:13 am, April 2, 2024

    These are actually wonderful ideas in concerning blogging.
    You have touched some good factors here. Any way keep up wrinting.

    my webpage vpn special coupon

  • vpn special coupon code 2024 at 10:14 pm, April 2, 2024

    This is a topic which is close to my heart…

    Thank you! Where are your contact details though?

    Feel free to visit my website :: vpn special coupon code 2024

  • Scrapebox List at 2:15 pm, April 3, 2024

    Good day! Do you know if they make any plugins to help with Search Engine
    Optimization? I’m trying to get my site to rank for some
    targeted keywords but I’m not seeing very good success.

    If you know of any please share. Thanks! I saw similar blog here: Backlink Building

  • List of Backlinks at 2:33 pm, April 3, 2024

    Hey there! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my website to rank for some targeted keywords but I’m
    not seeing very good results. If you know of any please share.
    Thanks! You can read similar article here: List of Backlinks

  • link building at 9:05 am, April 4, 2024

    Hello! Do you know if they make any plugins to help with SEO?
    I’m trying to get my site to rank for some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Kudos! You can read similar text here: Scrapebox List

  • vpn special coupon code 2024 at 6:23 pm, April 4, 2024

    What’s up, I would like to subscribe for this weblog
    to take most up-to-date updates, thus where can i do it please assist.

    My webpage; vpn special coupon code 2024

  • vpn coupon 2024 at 3:31 am, April 6, 2024

    Incredible points. Outstanding arguments. Keep up the good effort.

    Also visit my webpage: vpn coupon 2024

  • vpn special coupon at 2:21 pm, April 6, 2024

    Wow, amazing blog format! How long have you been blogging for?
    you made blogging glance easy. The total look of
    your website is fantastic, let alone the content material!

    Also visit my homepage :: vpn special coupon

  • vpn special at 11:29 am, April 11, 2024

    Hmm is anyone else experiencing problems with the pictures
    on this blog loading? I’m trying to determine if its a problem
    on my end or if it’s the blog. Any responses would be greatly appreciated.

    Look at my blog post: vpn special

Leave a comment

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

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
Glimpses into Technologies Used in Euro Cup, 2016

Big Data Jun 13th, 2016

Glimpses into Technologies Used in Euro Cup, 2016...

Read more

INQUIRY

Let's get in touch

UNITED STATES

31236 Meadowview Square,
Delmar, DE 19940, USA

Sales: +1 667 771 6758

UNITED KINGDOM

13 Layton Road, Hounslow,
London, TW3 1YJ

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

biolah

depo 25 bonus 25 to 5x

depo 25 bonus 25

depo 25 bonus 25

mndrmndr.com

bonusdeposit.net

https://www.greentourstanzania.com/wp-includes/customize/

https://temp1.novotest.biz/id/

depo 25 bonus 25

https://sumberjo-blitar.desa.id/images

https://sumberjo-blitar.desa.id/data

depo 25 bonus 25 to 5x

depo 25 bonus 25

https://www.greentourstanzania.com/wp-includes/js/product/

https://smpabbs.sch.id/gacor/100/

https://smpabbs.sch.id/gacor/bonus/

deposit 25 bonus 25

depo 25 bonus 25

bonus new member 100

https://ppdb.smk-kosgoro.sch.id/data/depo 25 bonus 25https://jesus.nouvellevie.com/wp-includes/images/Getoko.iddepo 25 bonus 25https://bonus-baru.s3.ap-southeast-1.amazonaws.com/link-daftar-slot-gacor.htmlhttps://bonus-baru.s3.ap-southeast-1.amazonaws.com/scatter-pink-paling-gacor.htmlhttps://worldlisteningproject.org/wp-includes/depo25bonus25/bonus new member 100depo 25 bonus 25