2012-04-18 14 views
13

Cách tốt nhất để thực thi các lệnh quản trị/giao diện mongodb lập trình từ node.js là gì? Cụ thể, tôi muốn xuất một bộ sưu tập mongodb bằng cách sử dụng mongodump sau khi thực hiện một loạt các chèn. Một cái gì đó như thế này:Làm cách nào để thực thi lệnh mongodump lập trình từ node.js?

// 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??? 

      }); 
     }); 
    } 
}); 

Trả lời

16

Hãy thử sử dụng 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

Đã hoạt động tốt. Cảm ơn. – TankofVines

1

Một năm khác nhau, một câu trả lời khác nhau.

Bạn có thể sử dụng một cái gì đó như Shelljs đến execmongodump hoặc bất kỳ lệnh nào khác mà trình bao UNIX cung cấp.

Các vấn đề liên quan