在本篇博客中,我们将详细介绍如何在Koa框架下连接MongoDB数据库,并创建数据模型。首先,我们需要安装mongoose库,然后配置数据库连接。接着,我们将创建一个基础模型,包含创建时间和更新时间字段。然后,我们将创建一个用户模型,包含用户名、邮箱、密码等字段,并使用md5进行密码加密。最后,我们将在controller中使用这个用户模型,实现一个查询用户的功能。
安装mongoose
首先,我们需要在项目中安装mongoose库,使用以下命令进行安装:
npm install mongoose
配置数据库连接
我们需要创建一个配置文件config/config.default.js,配置MongoDB数据库的连接路径:
module.exports.mongoPath = "mongodb://127.0.0.1:27017/express-video"
然后在model/index.js中,使用mongoose.connect()方法连接数据库:
const mongoose = require('mongoose')
const { mongoPath } = require('../config/config.default')
async function main(){
await mongoose.connect(mongoPath)
}
main()
.then(res=>{
console.log('mongoDB 连接成功');
})
.catch(err=>{
console.log(err);
})
创建基础模型
我们创建一个基础模型baseModel.js,包含创建时间和更新时间字段,这两个字段在大多数模型中都会用到:
module.exports = {
createAt:{
type:Date,
default:Date.now()
},
updateAt:{
type:Date,
default:Date.now()
}
}
创建用户模型
我们创建一个用户模型userModel.js,包含用户名、邮箱、密码等字段。密码字段使用md5进行加密,保证用户密码的安全性:
const mongoose = require('mongoose')
const md5 = require('../util/md5')
const baseModel = require('./baseModel')
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true,
set: value => md5(value),
select:false
},
phone: {
type: String,
required: true
},
image: {
type: String,
default: null
},
cover:{
type: String,
default: null
},
channelDes:{
type: String,
default: null
},
subscribeCount:{
type:Number,
default:0
},
...baseModel
})
module.exports = userSchema
创建md5加密util/md5.js
const crypto = require('crypto')
module.exports = str =>{
return crypto.createHash('md5').update('by'+str).digest('hex')
}
在controller中使用模型
最后,我们在controller中使用用户模型,实现一个查询用户的功能。我们可以通过用户ID查询用户信息,验证我们的模型是否正确:
const { User } = require('../model')
module.exports.index = async (ctx, next) => {
let user = await User.findById(ctx.params.userId)
ctx.body = user
}
在路由配置中,添加对应的路由:
router.get('/user/:userId', userController.index)
总结
以上就是在Koa框架下连接MongoDB数据库,并创建数据模型的详细步骤。希望对你有所帮助。