Express框架访问MongoDB数据库

郎鹤龄
2023-12-01

Express框架访问MongoDB数据库

1.npm安装(npm i nodemon/cors/mongoose)
2.检查端口号
1.dao层

​ ①、config(数据库连接)

//1.导入mongoose模块
const Mongoose = require('mongoose')

//2.定义mongodb数据库的连接字符串:协议://主机名/主机地址/端口号/数据库名

const mdb_url = 'mongodb://localhost:27017/my_test'

//3.建立和mongodb数据库连接
Mongoose.connect(mdb_url,{useNewUrlParser:true,useUnifiedTopology:true})

//4.对连接过程进行处理
//4.1建立连接-----连接成功触发connected事件
Mongoose.connection.on('connected',function (){
    console.log('mongodb数据库连接成功!连接地址是:'+mdb_url)
})

//4.2连接异常----回调函数的参数中保留了异常的信息
Mongoose.connection.on('error',function (){
    console.log('数据库连接异常'+err)
})

//4.3断开连接
Mongoose.connection.on('disconnectiede',function (){
    console.log('断开数据库的连接!')
})

//5.导出Mongoose
module.exports = Mongoose

​ ②、model(创建数据库中的集合)

//1.导入配置文件
const Mongoose = require('../config/dbconfig')

//2.导入Schema
const Schema = Mongoose.Schema

//3.定义Schema:要和数据库中的集合对应(Schema属性对象集合中的键)
const BlogSchema = new Schema({
    blogId:{type:String,unique:true},
    type:{type:String},
    title:{type:String},
    content:{type:String},
    author:{type:String},
    // creatAt:{type:Date}
},{
    versionKey:false,//去掉文档中的_v
    timestamps:{//时间戳
        createdAt:true,
        updatedAt:false
    }
})

//5.导出model,可以使用model操作数据库
module.exports = Mongoose.model('BlogModel',BlogSchema,'blog111')

​ ③、操作层(增删改查层),添加

const BlogModel = require('../model/blogmodel')

exports.insertBlog =async function (blog){
    return await BlogModel.create(blog)
}
exports.removeBlog =async function (b_id){
    return await BlogModel.delete({
        blogId:b_id
    })
}

exports.modifyBlog = async function(blog){
    return await BlogModel.updateOne({blogId:blog.blogId}, {$set:{type:blog.type, title:blog.title, content:blog.content}})
}
exports.queryAll = async function(){
    return await BlogModel.find()
}
2.service层:调用dao层访问数据库,接受客户端信息,经过处理返回给客户端
const blogDao = require('../dao/crud/blogdao')

var num = 1
exports.addBlog = function (req,res){
    let date = new Date()
    //let str = date.getFullYear()+
    let blog = {
        blogId:'blog-' +date.getTime(),
        title:req.body.blogTitle,
        content:req.body.blogContent,
        type:req.body.blogType,
        author:'张三',
        // createAt:date
    }
    blogDao.insertBlog(blog).then(result=>{
        res.json({
            code:2000,
            info:result
        })
    }).catch(e=>{
        console.log(e)
    })
}
3.接口层:路由接口
const express= require('express')
const router = express.Router()



const blogService = require('../../service/blogservice')


//增加  http://localhost:9000/blogapi/addBlog
router.post('/addBlog',blogService.addBlog)
module.exports = router
目的:
1.学会代码封装:dao层、service层、接口层
2.MVC设计思想:M(Model)、V(View)、C(Controller)
 类似资料: