mongoose代码的模块化


✅ 目录结构示例

project/
├── config/
│   └── db.config.js         # 数据库配置
├── models/
│   └── user.model.js        # 用户模型
├── services/
│   └── user.service.js      # 用户服务层
├── db/
│   └── mongoose.js          # 数据库连接模块
├── index.js                 # 项目入口

📁 1. config/db.config.js —— 配置文件

// config/db.config.js
module.exports = {
  host: 'localhost',
  port: 27017,
  dbName: 'modularDemo',
  options: {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }
}

📁 2. db/mongoose.js —— 连接数据库模块

// db/mongoose.js
const mongoose = require('mongoose')
const config = require('../config/db.config')

const uri = `mongodb://${config.host}:${config.port}/${config.dbName}`

const connectDB = async () => {
  try {
    await mongoose.connect(uri, config.options)
    console.log('✅ MongoDB connected successfully')
  } catch (error) {
    console.error('❌ MongoDB connection failed:', error)
    process.exit(1)
  }
}

module.exports = connectDB

📁 3. models/user.model.js —— 用户模型

// models/user.model.js
const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: { type: Number, min: 0 },
  email: { type: String, unique: true, required: true },
  isActive: { type: Boolean, default: true }
})

module.exports = mongoose.model('User', userSchema)

📁 4. services/user.service.js —— 用户服务操作

// services/user.service.js
const User = require('../models/user.model')

const createUser = async (data) => await User.create(data)

const getAllUsers = async () => await User.find()

const findUserByEmail = async (email) => await User.findOne({ email })

const updateUser = async (id, data) =>
  await User.findByIdAndUpdate(id, data, { new: true })

const deleteUser = async (id) => await User.findByIdAndDelete(id)

module.exports = {
  createUser,
  getAllUsers,
  findUserByEmail,
  updateUser,
  deleteUser
}

📁 5. index.js —— 启动项目、测试服务

// index.js
const connectDB = require('./db/mongoose')
const userService = require('./services/user.service')

const run = async () => {
  await connectDB()

  // 插入一个新用户
  const newUser = await userService.createUser({
    name: 'Tom',
    age: 25,
    email: 'tom@example.com'
  })
  console.log('🆕 Created user:', newUser)

  // 查询所有用户
  const users = await userService.getAllUsers()
  console.log('👥 All users:', users)
}

run()

📝 说明

  • 所有配置集中在 config/db.config.js
  • 连接逻辑独立在 db/mongoose.js
  • 模型和服务模块分离,便于维护
  • 可方便接入 Express、Koa 等后端框架

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻小胖

如果觉得不错就给点赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值