依赖
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.12.0"
}
入口文件
集成了express和mongodb,其中user是express的导出路由
import express from 'express'; import http from 'http'; import user from './mongodb/user/index.js'; import mongodbServer from './mongodb/index.js'; import bodyParser from 'body-parser'; const app = express(); const port = 3000; const server = http.createServer(app); mongodbServer(); app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json app.use('/user', user); server.listen(port, () => console.log(`base-app listening on port ${port}!`));
mongodb入口
一些基本的配置信息
import mongoose from 'mongoose'; function run() { console.log('连接到mongodb数据库...'); mongoose.set('useCreateIndex', true); mongoose.set('bufferCommands', false); mongoose.connect( 'mongodb://localhost:27017', { dbName: 'test', useNewUrlParser: true, useUnifiedTopology: true, keepAlive: true }, function (error) { if (error) { console.error('mongodb连接失败!'); console.log(error); } } ); const db = mongoose.connection; db.once('open', function () { console.log('mongodb连接成功!'); }); } export default run;
user路由模块入口文件
基于mongoose对数据库实体进行简单的封装,以及一些增删改查基本操作
import express from 'express'; import mongoose from 'mongoose'; import getUser from './getUser.js'; import addUser from './addUser.js'; import updateUser from './updateUser.js'; import delUser from './delUser.js'; const router = express.Router(); const Schema = mongoose.Schema; const userSchema = new Schema({ // 用户名 name: { type: String, unique: true, required: true }, // 密码 password: { type: String, required: true }, // 头像 avatar: { type: String }, // 角色 role: { type: String, enum: ['admin', 'operator'], required: true, default: 'operator' }, // 创建日期 createDate: { type: Date, default: new Date() } }); const User = mongoose.model('user', userSchema, 'user'); // 查询用户 router.get('/get', (req, res, next) => { const { name } = req.query; getUser({ name }) .then(doc => { res.json({ code: 0, data: doc }); }) .catch(err => { res.json({ code: -1, message: err }); }); }); // 新增用户 router.post('/add', (req, res, next) => { const { name, password, avatar, role } = req.body; addUser({ name, password, avatar, role }) .then(() => { res.json({ code: 0, message: '保存成功' }); }) .catch(err => { res.json({ code: -1, message: err }); }); }); // 删除用户 router.post('/del', (req, res, next) => { const { name } = req.body; delUser({ name }) .then(() => { res.json({ code: 0, message: '删除成功' }); }) .catch(err => { res.json({ code: -1, message: err }); }); }); // 更新用户 router.post('/update', (req, res, next) => { const { name, password } = req.body; updateUser({ name, password }) .then(() => { res.json({ code: 0, message: '保存成功' }); }) .catch(err => { res.json({ code: -1, message: err }); }); }); export { User }; export default router;
具体增删改查文件
import { User } from './index.js'; export default function (params) { return new Promise((resolve, reject) => { if (!params.name) { reject('缺少用户名'); } if (!params.password) { reject('缺少密码'); } new User(params) .save() .then(() => { resolve(); }) .catch(err => { if (err.message.indexOf('duplicate key error') !== -1 && err.keyValue.name) { reject('用户名已存在'); } }); }); }
import getUser from './getUser.js'; export default function (params) { return new Promise((resolve, reject) => { getUser(params) .then(doc => { doc.remove().then(() => { resolve(); }); }) .catch(err => { reject(err); }); }); }
import getUser from './getUser.js'; export default function (params) { return new Promise((resolve, reject) => { getUser(params) .then(doc => { doc.updateOne(params).then(() => { resolve(); }); }) .catch(err => { reject(err); }); }); }
import { User } from './index.js'; export default function ({ name }) { return new Promise((resolve, reject) => { if (!name) { reject('缺少用户名'); } User.findOne({ name }).then(doc => { if (doc) { resolve(doc); } else { reject('未查询到用户信息'); } }); }); }
文件目录结构
├─src
├─mongodb
├─user
├─index.js
├─addUser.js
├─delUser.js
├─updateUser.js
├─getUser.js
├─index.js
├─main.js