its me
its me

Reputation: 542

How to backup a mongodb collection using express.js and Node.js

I want to take a backup of my userdatas collection every month.

Backup means:

I need to take userdatas data and store it in some backupuserdatas collection. Every 1 month a batch program should run automatically and should store that month of data(documents) in the backupuserdatas collection.

I have used node-cron for running batch programs but I don't know to write a query for backing up my userdatas collection every month.

How can I do this in Node.js, express.js and mongodb?

Upvotes: 1

Views: 14911

Answers (3)

Abdul Saleem
Abdul Saleem

Reputation: 10622

mongodb-snapshot

https://github.com/lihaibh/mongodb-snapshot/tree/83b12d377a1ec387f0bcf121b294cdd45504ac76

install

npm i mongodb-snapshot

add this function

async function mongoSnap(path, restore = false) {
    const mongo_connector = new BKP.MongoDBDuplexConnector({
        connection: { uri: mongoCString, dbname: dbName }
    });
    const localfile_connector = new BKP.LocalFileSystemDuplexConnector({
        connection: { path: path }
    });
    const transferer = restore ? 
        new BKP.MongoTransferer({ source: localfile_connector, targets: [mongo_connector] }) : 
        new BKP.MongoTransferer({ source: mongo_connector, targets: [localfile_connector] }) ;
    for await (const { total, write } of transferer) { }
}

use like

await mongoSnap('./backups/collections.tar'); // backup

await mongoSnap('./backups/collections.tar', true); // restore

Upvotes: 2

Naveenkumar Bobbadi
Naveenkumar Bobbadi

Reputation: 21

You can use below modules https://www.npmjs.com/package/mongodb-backup https://www.npmjs.com/package/mongodb-restore

You can also take the backup and restore the specific collections using options

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 2241

You can run find query on userdatas table and than inside it use insert query to insert data in backupuserdatas table.

I know it's not a good solution but for small data you can use it.

For running multiple queries inside you need to use Async for synchronize behavior of node. Hope this will help you.

You can do it by using following code in your node-cron section like this:

mongoose.users.find({}, function(err, result){
    var data = {};
    var curr_date = new Date();
    data["user_data"] = result;
    data["created"] = curr_date;
    var savebackup = new mongoose.backup_user(data);
    savebackup.save(function(err,res){
        // save done
        mongoose.users.remove({}, function(err, result){});
    });
});

Here I created one backup table named "backup_user" and the user table is "users".

This will save your all users data to backup_user table each time you run your node-cron api.

Upvotes: 1

Related Questions