2012-04-18 3 views
13

mongodb admin/consoleコマンドをnode.jsからプログラムで実行する最良の方法は何ですか?具体的には、一連の挿入を実行した後でmongodumpを使用してmongodbコレクションをエクスポートしたいと考えています。このような何か:node.jsからプログラムでmongodumpコマンドを実行するにはどうすればよいですか?

// requires and initializing stuff left out for brevity 
db.open(function(err, db) { 
    if(!err) { 
     db.collection('test', function(err, collection) { 
      var docs = [{'hello':'doc1'}, {'hello':'doc2'}, {'hello':'doc3'}]; 

      collection.insert(docs, {safe:true}, function(err, result) { 

       // Execute mongodump in this callback??? 

      }); 
     }); 
    } 
}); 

答えて

16

child_process.spawn(command, args)を使用してみてください:

var spawn = require('child_process').spawn; 

// ... 
    collection.insert(docs, {safe:true}, function(err, result) { 
    var args = ['--db', 'mydb', '--collection', 'test'] 
     , mongodump = spawn('/usr/local/bin/mongodump', args); 
    mongodump.stdout.on('data', function (data) { 
     console.log('stdout: ' + data); 
    }); 
    mongodump.stderr.on('data', function (data) { 
     console.log('stderr: ' + data); 
    }); 
    mongodump.on('exit', function (code) { 
     console.log('mongodump exited with code ' + code); 
    }); 
    }); 
// ... 
+1

うまく機能しました。ありがとう。 – TankofVines

1

異なる年、別の答えを。

あなたはShelljs mongodumpexecまたはUNIXシェルが提供する任意の他のコマンドのようなものを使用することができます。