How to set up automatic backups for MongoDB using Node.js

How to set up automatic backups for MongoDB using Node.js

With a couple of dependencies and some JavaScript, you can set up automatic backups on your servers for your MongoDB instances.

This tutorial describes the process for setting up automatic backups for MongoDB using Node.js. Before we dive into this two-step process, you need a couple of prerequisites.

  • Fs and lodash npm modules should be installed.
  • Make sure that your MongoDB is protected with a username and password. If they aren't, follow the steps here.

Step 1

Create a JavaScript file in your project folder called mongodb_backup.js and add the code below. Of course, you'll want to replace the 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 ' + + ' --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 a cron, install the cron module from NPM package manager using npm install cron --save. Add the code below into your server.js/main.js/index.js global.CronJob = require(‘Your path to cron.js file’);. Now create a cron.js file in your project and paste the code below into it.

var CronJob = require('cron').CronJob;
var Cron = require('./mongodb_backup.js');
new CronJob('0 0 0 * * *', function() {
}, null, true, 'America/New_York');

Thanks for reading ! This is image title

node-js mongodb

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Ecommerce MERN(MongoDB Express.js React.js Node.js) Redux Tailwind

Ecommerce MERN(MongoDB Express.js React.js Node.js) Redux Tailwind

Node.js Express MongoDB Tutorial

Node.js Express MongoDB Tutorial is CRUD example, I have created to showcase Express web framework, MongoDB NoSQL database, and Node.js server platform.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Build a REST API using Node.js, Express.js, Mongoose.js and MongoDB

Node.js, Express.js, Mongoose.js, and MongoDB is a great combination for building easy and fast REST API. You will see how fast that combination than other existing frameworks because of Node.js is a packaged compilation of Google’s V8 JavaScript engine and it works on non-blocking and event-driven I/O. Express.js is a Javascript web server that has a complete function of web development including REST API.