Spaces:
Sleeping
Sleeping
| const mongoose = require('mongoose'); | |
| const logger = require('../utils/logger'); | |
| const connectDB = async () => { | |
| try { | |
| const conn = await mongoose.connect(process.env.MONGODB_URI, { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| }); | |
| logger.info(`MongoDB Connected: ${conn.connection.host}`); | |
| // 创建默认管理员用户和默认分类 | |
| await createDefaultAdmin(); | |
| await createDefaultCategories(); | |
| } catch (error) { | |
| logger.error(`Error connecting to MongoDB: ${error.message}`); | |
| process.exit(1); | |
| } | |
| }; | |
| const createDefaultAdmin = async () => { | |
| try { | |
| const User = require('../models/User'); | |
| // 先检查环境变量 | |
| if (!process.env.ADMIN_USERNAME || !process.env.ADMIN_PASSWORD) { | |
| logger.warn('管理员账户环境变量未设置,跳过默认管理员创建'); | |
| return; | |
| } | |
| // 检查是否已存在管理员用户 | |
| const adminExists = await User.findOne({ username: process.env.ADMIN_USERNAME }); | |
| if (!adminExists) { | |
| // 不手动哈希密码,让模型的中间件处理加密 | |
| const admin = await User.create({ | |
| username: process.env.ADMIN_USERNAME, | |
| password: process.env.ADMIN_PASSWORD, // 直接使用原始密码 | |
| isAdmin: true | |
| }); | |
| logger.info(`默认管理员创建成功: ${admin._id}`); | |
| } else { | |
| logger.info('管理员账户已存在,无需创建'); | |
| } | |
| } catch (error) { | |
| logger.error(`创建默认管理员出错: ${error.message}`); | |
| } | |
| }; | |
| const createDefaultCategories = async () => { | |
| try { | |
| const Category = require('../models/Category'); | |
| // 检查是否已有分类 | |
| const categoriesCount = await Category.countDocuments(); | |
| if (categoriesCount === 0) { | |
| // 创建默认分类 | |
| const defaultCategories = [ | |
| { name: '通用', color: '#007AFF' }, | |
| { name: '工作', color: '#FF9500' }, | |
| { name: '学习', color: '#4CD964' }, | |
| { name: '创意', color: '#FF2D55' } | |
| ]; | |
| await Category.insertMany(defaultCategories); | |
| logger.info('Default categories created'); | |
| } | |
| } catch (error) { | |
| logger.error(`Error creating default categories: ${error.message}`); | |
| } | |
| }; | |
| module.exports = { connectDB }; |