const { connectDB, mongoose } = require('./server/db/mongoose'); const bcrypt = require('bcryptjs'); // 引入User模型 const User = require('./server/models/User'); // 要设置的管理员信息 const adminInfo = { email: 'admin@example.com', password: 'Admin123!' }; async function updateAdminUser() { try { console.log('正在连接数据库...'); // 连接数据库 const connection = await connectDB(); // 检查连接状态 if (!connection || mongoose.connection.readyState !== 1) { throw new Error('数据库连接失败'); } console.log('数据库连接成功,开始更新管理员账户...'); // 查找管理员用户 const adminUser = await User.findOne({ role: 'admin' }); if (!adminUser) { console.log('未找到管理员账户,创建新的管理员账户...'); // 加密密码 const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(adminInfo.password, salt); // 创建管理员用户 const newAdmin = new User({ username: 'admin', email: adminInfo.email, password: hashedPassword, role: 'admin', credits: 100, isEmailVerified: true, status: 'active' }); await newAdmin.save(); console.log('新管理员账户创建成功'); } else { console.log('找到管理员账户,更新中...'); // 更新管理员信息 adminUser.email = adminInfo.email; adminUser.password = adminInfo.password; // 密码将通过User模型的save中间件自动加密 await adminUser.save(); console.log('管理员账户更新成功'); } // 关闭数据库连接 await mongoose.disconnect(); console.log('数据库连接已关闭'); process.exit(0); } catch (error) { console.error('更新管理员账户时出错:', error); process.exit(1); } } // 执行更新 updateAdminUser();