目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/21b97ea8f30e2901f6c7a0f2061f8e3e.png)
连接数据库
1. config/dbconfig.js
const Mongoose = require('mongoose')
const url = 'mongodb://localhost:27017'
const dbName = 'youth'
const connectUrl = url + '/'+ dbName
Mongoose.connect(connectUrl, { useNewUrlParser: true, useUnifiedTopology: true })
Mongoose.connection.on('connected', function () {
console.log('数据库连接成功!连接地址是:' + connectUrl)
})
Mongoose.connection.on('error', function (err) {
console.log('数据库连接异常!' + err)
})
Mongoose.connection.on('disconnectied', function () {
console.log('断开数据库的连接!')
})
module.exports = {
Mongoose
}
2. app.js
require('./config/dbconfig');
数据表连接:model层
var Mongoose = require('mongoose');
const Schema = Mongoose.Schema
const UserSchema = new Schema({
userId: { type: String, unique: true },
userName: { type: String, unique: true },
createTime: { type: String },
email: { type: String, unique: true },
passWord: { type: String },
roleId: { type: String },
})
module.exports = Mongoose.model('Users', UserSchema)
数据库操作(dao层)
const UserModel = require('../../model/userModel')
exports.insertUser = async function (data) {
return await UserModel.create(data)
}
exports.removeUser = async function (id) {
return await UserModel.delete({
userId: id
})
}
exports.modifyUser = async function (data) {
return await UserModel.updateOne(
{ userId: data.userId },
{ $set: {
passWord: data.passWord,
roleId: data.roleId,
} }
)
}
exports.queryAll = async function (data) {
return await UserModel.find(data)
}
数据操作(service层)
const userDao = require('../dao/crud/userDao')
exports.addUser = function (req, res) {
console.log(req)
let date = new Date()
let data = {
userId: 'user-' + date.getTime(),
createTime: new Date().toLocaleString(),
...req.query
}
userDao.insertUser(data).then(result => {
res.send({
code: 2000,
info: result
})
console.log(result)
}).catch(e => {
res.send(e)
})
}
接口(router层)
1. route/user.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
const userService = require('../service/userService')
router.get('/addUser', userService.addUser);
module.exports = router;
2.注册(app.js)
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
app.use('/', indexRouter);
app.use('/user', usersRouter);