You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Node.js轻松实现MongoDB备份 认证及参数报错解决

Node.js 服务端MongoDB备份修复方案

报错原因说明

两个报错分别对应独立问题:

  1. 初始运行抛出unauthorized command listCollections requires authentication:MongoDB开启了身份认证,调用mongodump时未传入认证信息,进程无权限读取数据库集合列表。
  2. 添加--uri参数后触发"不是函数"报错:参数数组中--uri所在行末尾漏写逗号,JavaScript解析时将相邻的两个模板字符串识别为函数调用(即把--uri对应的字符串当成函数,传入--archive对应的字符串执行),触发类型错误。

额外提示:使用--uri传入完整MongoDB连接串时,连接串已经包含数据库地址、认证信息、目标库名等配置,无需额外传入--db参数,避免参数冲突。

修正后可直接运行的代码

首先确认配置中的config.MONGODB_URI_SERVER为标准格式连接串,示例:mongodb://[用户名]:[密码]@[数据库地址]:[端口]/pors_db?authSource=admin,再按如下代码修改即可:

const root = require('./root');
const { spawn } = require('child_process');
const config = require('../config.json');
const fs = require('fs');
const path = require('path');

setTimeout(() => {
    backupMongoDB();
}, 1000);

function backupMongoDB() {    
    const DB_NAME = 'pors_db';
    const DATE = getTodayDate();
    const backupDir = path.join(root, 'db_backup');
    // 自动创建备份目录,避免首次运行因路径不存在报错
    if (!fs.existsSync(backupDir)) {
        fs.mkdirSync(backupDir, { recursive: true });
    }
    const ARCHIVE_PATH = path.join(backupDir, `${DB_NAME}-${DATE}.gzip`);
    const child = spawn('mongodump', [
        `--uri=${config.MONGODB_URI_SERVER}`,
        `--archive=${ARCHIVE_PATH}`,
        '--gzip',
    ]);

    child.stdout.on('data', (data) => {
        console.log('stdout:\n', data.toString());
    });

    child.stderr.on('data', (data) => {
        console.log('stderr:\n', data.toString());
    });

    child.on('error', (error) => {
        console.log('backup process error:\n', error);
    });
    
    child.on('exit', (code, signal) => {
        if(code) {
            console.log('Process exit with code:', code);
        } else if(signal) {
            console.log('Process killed with signal:', signal);
        } else {
            console.log('Backup completed successfully.');
        }
    });

    function getTodayDate() {
        const date = new Date();
        const dd = String(date.getDate()).padStart(2, '0');
        const mm = String(date.getMonth() + 1).padStart(2, '0'); 
        const yyyy = date.getFullYear();
        return `${yyyy}-${mm}-${dd}`;
    }
}

module.exports = backupMongoDB;

常见运行问题排查

  • 若提示mongodump: command not found:说明MongoDB数据库工具未加入系统环境变量,直接替换spawn第一个参数为mongodump的绝对路径即可(Linux默认路径通常为/usr/bin/mongodump,Windows可在MongoDB安装目录的Tools文件夹下找到对应exe)
  • 若仍提示权限错误:检查连接串中的数据库账号是否拥有目标库的读取权限,若账号是管理员账号需确认连接串末尾添加了authSource=admin参数指定认证库
  • 若提示写入文件失败:确认运行Node.js服务的系统账号对db_backup目录有读写权限

内容的提问来源于stack exchange,提问作者Sara Ree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 19:18:17