在这里,我将在 MERN 项目中备份MongoDB Atlas 数据库。我使用以下代码进行备份,但是运行快递服务器时会显示此消息。首先创建mongodb_backup.js,cron.js并需要server.js文件。这些都工作正常。 还有一件事是提供给dbOptions.host的正确URL。
mongodb_backup.js
var fs = require('fs');
var _ = require('lodash');
var exec = require('child_process').exec;
const path = require('path');
const backupDirPath = path.join(__dirname, 'database-backup/');
var dbOptions = {
user: '****',
pass: '****',
host: 'mongodb+srv://cluster0-gtick.mongodb.net/test?retryWrites=true&w=majority',
port: 27017,
database: 'Project-Management',
autoBackup: true,
removeOldBackup: true,
keepLastDaysBackup: 2,
autoBackupPath: backupDirPath
};
exports.stringToDate = dateString => {
-------------------- all works fine
};
exports.empty = mixedVar => {
------------------------all works fine
};
// Auto backup function
exports.dbAutoBackUp = () => {
if (dbOptions.autoBackup == true) {
let date = new Date();
let beforeDate, oldBackupDir, oldBackupPath;
currentDate = this.stringToDate(date);
let newBackupDir = ------;
let newBackupPath = dbOptions.autoBackupPath + '-mongodump-' + newBackupDir;
if (dbOptions.removeOldBackup == true) {
-------------all works fine
}
// Command for mongodb dump process
let cmd =
'mongodump --host ' +
dbOptions.host +
' --port ' +
dbOptions.port +
' --db ' +
dbOptions.database +
' --username ' +
dbOptions.user +
' --password ' +
dbOptions.pass +
' --out ' +
newBackupPath;
exec(cmd, (error, stdout, stderr) => {
if (this.empty(error)) {
// check for remove old backup after keeping # of days given in configuration.
if (dbOptions.removeOldBackup == true) {
if (fs.existsSync(oldBackupPath)) {
exec('rm -rf ' + oldBackupPath, err => { });
}
}
}
else{
console.log(stderr); //here consoling the error
}
});
}
};