①、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()
}
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)
})
}
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