ffxsam
ffxsam

Reputation: 27713

How to write Node.js based cron job to drop MongoDB collections and issue db.copyDatabase command

I need to write a nightly cron job (using Lambda + Node.js) that will drop all collections in Database B, then use db.copyDatabase to copy Database A to Database B. I know how to do all these operations manually via the mongo client, but not sure how to do it in JavaScript.

Ideally it would be good to use https://mongodb.github.io/node-mongodb-native/ to do so, though I don't see a way to invoke raw commands such as db.copyDatabase.

Upvotes: 1

Views: 554

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

You will need to run it as a command:

const assert = require('assert');
const MongoClient = require('mongodb').MongoClient;

var const = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function(err, db) {
    if (err) {
        console.log(err);
    }
    else {

        const mongoCommand = { copydb: 1, fromhost: "localhost", fromdb: "test", todb: "test_dup" };
        const admin = db.admin();

        admin.command(mongoCommand, function(commandErr, data) {
            if (!commandErr) {
                console.log(data);
            } else {
                console.log(commandErr.errmsg);
            }
            db.close();
        });
    }
});

Upvotes: 2

Related Questions