2

I do have a shell script that invokes

mongo --eval "db.copyDatabase('somedatabase', 'somedatabase_duplicate', 'sourcehost')"

to copy a database.

Currently I am stuck with doing the same from within a Node.JS application. Calling

mongoCommand = `db.copyDatabase("somedatabase", "somedatabase_duplicate", "localhost")`;
db.command(mongoCommand, function(commandErr, data) {
      if(!commandErr) {
        log.info(data);
      } else {
        log.error(commandErr.errmsg);
      }
    });

Always resulsts in a "no such command" error message.

Edit for clarification: Using db.admin().command() results in the same problem and using the command suggested in enter link description here, too.

What's the correct way to call this command or, alternatively, to clone a database from Node.JS?

1

2 Answers 2

3

Well, you are trying to copy database which is administration operation so have to do with admin account. Again, to copy database command is copydb.

try running this command in shell, db.copyDatabase and you'll see source of command.

try:

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


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

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

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

        admin.command(mongoCommand, function(commandErr, data) {
            if (!commandErr) {
                console.log(data);
            } else {
                console.log(commandErr.errmsg);
            }
            db.close();
        });
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't seem to do anything. The callback is never run. node just exits and I see nothing in the MongoDB logs.
Check if you have database copy on your server? Also make sure you have permissions to access admin database. In my case, I see message { ok: 1 }
I get zero output and no new database. When using the batch file, it works. That's what I can't wrap my head around.
What versions of node / driver / mongodb did this work with? I just tried this with node.js 9.11.1, mongodb (npm package) 3.1.1, mongo (shell) 3.2.6 and it gave me db.admin is not a function
@Wyck try: db.mongodb.db.admin
0
//core modules
const assert = require('assert')
const MongoClient = require('mongodb').MongoClient;
const moment = require('moment');
const mongo = require('mongodb')

//custom modules
let { ip, port, database } = require('./dbUpgradeConfig')
const url = `mongodb://${ip}:${port}`
let todayDate = moment().format('DD/MM/YYYY HH:mm')
console.log(todayDate)
const myDate = new Date()
console.log(myDate)
var d = Date(Date.now());
// Converting the number of millisecond in date string 
a = d.toString()

// Options for mongoDB
const mongoOptions = { useNewUrlParser: true }
let db


//TODO: handle reconnect
let connect = () => {
    return new Promise((resolve, reject) => {
        if (db) resolve()
        else {
            mongo.connect(url, mongoOptions, (err, client) => {
                if (err) reject(err)
                else {
                    db = client.db(database)
                    resolve()
                }
            })
        }
    })
}


/**
 * @description create duplicate database from current database in mongodb 
 */
let CloneDb = () => {
    return new Promise((resolve, reject) => {
        connect()
            .then(() => {
                console.log(db)
                let mongoCommand = { copydb: 1, fromhost: "localhost", fromdb: "db_name", todb: "db_name_duplicate" }
                let adminDB = db.admin()

                adminDB.command(mongoCommand, function (commandErr, data) {
                    if (!commandErr) {
                        console.log(data)
                    } else {
                        console.log(commandErr.errmsg)
                    }

                });
            })
    })
}

CloneDb().then(data => {
    // debugger;
    console.log("The clone db", data)
})  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.