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?

Community
  • 1
  • 1
Sascha Kaupp
  • 282
  • 2
  • 14
  • 1
    Possible duplicate of [Clone database in Mongodb between hosts using node driver](http://stackoverflow.com/questions/16576541/clone-database-in-mongodb-between-hosts-using-node-driver) – Sterling Archer Apr 04 '16 at 14:01

2 Answers2

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();
        });
    }
});
Saleem
  • 8,728
  • 2
  • 20
  • 34
  • This doesn't seem to do anything. The callback is never run. node just exits and I see nothing in the MongoDB logs. – Sascha Kaupp Apr 04 '16 at 14:51
  • 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 }` – Saleem Apr 04 '16 at 14:57
  • 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. – Sascha Kaupp Apr 04 '16 at 15:03
  • 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 Aug 01 '18 at 01:21
  • @Wyck try: db.mongodb.db.admin – felipekm Nov 15 '18 at 14:36
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)
})