Koa.js中mongodb库封装
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
// config.js配置文件
var app = {
dbUrl:'mongodb://localhost:27017',//数据库地址
dbName:"koa"//数据库名称
}
module.exports = app;
//引入模块
const MongoDB = require('mongodb');
const MongoClient =MongoDB.MongoClient
const ObjectID = MongoDB.ObjectID;
const Config = require("./config.js");
class Db{
static getInstance(){//解决多次实例化 实例不共享的问题
if(!Db.instance){
Db.instance = new Db();
}
return Db.instance;
}
constructor(){
this.dbClient = "";
}
connect(){
let _that = this;
return new Promise((resolve,reject)=>{
if(!_that.dbClient){//解决数据库多次连接的问题
消除 DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { //useUnifiedTopology: true } to the MongoClient constructor.这个警告可以在 MongoClient.connect方法
的第二个参数传入{useUnifiedTopology: true }
MongoClient.connect(Config.dbUrl,{useUnifiedTopology: true },function(err, client) {
if(err){
reject(err);
}else{
_that.dbClient = client.db(Config.dbName);
resolve(_that.dbClient)
}
//client.close();先不关闭
});
}else{
resolve(_that.dbClient);
}
})
}
find(collectionName,json){
return new Promise((resolve,reject)=>{
this.connect().then(function(db){
var result = db.collection(collectionName).find(json);
result.toArray(function(err,docs){
if(err){
reject(err);
}else{
resolve(docs);
}
})
})
})
}
update(collectionName,json1,json2){
return new Promise((resolve,reject)=>{
this.connect().then((db)=>{
db.collection(collectionName).updateOne(json1,{
$set:json2
},(err,result)=>{
if(err){
reject(err);
}else{
resolve(result);
}
})
})
})
}
insert(collectionName,json){
return new Promise((resolve,reject)=>{
this.connect().then((db)=>{
db.collection(collectionName).insertOne(json,(err,result)=>{
if(err){
reject(err);
}
resolve(result);
})
})
})
}
delete(collectionName,json){
return new Promise((resolve,reject)=>{
this.connect().then((db)=>{
db.collection(collectionName).removeOne(json,(err,result)=>{
if(err){
reject(err);
}else{
resolve(result);
}
})
})
})
}
// 把id转换为mongodb中的ObjectID对象,便于数据修改删除等操作
getObjectId(id){
return new ObjectID(id);
}
}
module.exports = Db.getInstance();
//使用
const Koa = require('koa');
const path = require("path");
const render = require('koa-art-template');
var router = require('koa-router')();//初始化
const DB = require("./module/db.js");
const bodyParser = require('koa-bodyparser');
const static = require("koa-static");
const app = new Koa();
render(app, {
root: path.join(__dirname, 'views'),
extname: '.html',
debug: process.env.NODE_ENV !== 'production'
});
app.use(bodyParser());
//静态资源中间件可以配置多个
app.use(static(__dirname + '/static'));
// app.use(async function (ctx) {
// await ctx.render('user');
// });
router.get("/",async (ctx)=>{
var result = await DB.find("user",{});
await ctx.render('user',{
list:result
});
})
router.get("/add",async (ctx)=>{
await ctx.render('add');
})
router.post("/doAdd",async (ctx)=>{
var data = await DB.insert("user",ctx.request.body);
try {
if(data.result.ok == 1){
console.log("增加成功");
ctx.redirect("/");
}
} catch (error) {
console.log(error);
ctx.redirect("/add");
}
})
router.get("/edit",async (ctx)=>{
let id = ctx.query.id;//get方法获取id
console.log(ctx.query);
let data = await DB.find('user',{"_id":DB.getObjectId(id)})
await ctx.render('edit',{
list:data[0]
});
})
router.post("/doEdit",async (ctx)=>{
let id = ctx.request.body.id;//post方法获取id
var json2={
username:ctx.request.body.username,
age:ctx.request.body.age,
sex:ctx.request.body.sex
}
var data = await DB.update("user",{"_id":DB.getObjectId(id)},json2);
try {
if(data.result.ok == 1){
console.log("编辑成功")
ctx.redirect("/");
};
} catch (error) {
if(error){
ctx.redirect("/edit");
}
}
})
router.get("/delete",async (ctx)=>{
let id = ctx.query.id;
var data = await DB.delete("user",{"_id":DB.getObjectId(id)});
try {
if(data.result.ok == 1){
console.log("删除成功")
ctx.redirect("/");
};
} catch (error) {
if(error){
console.log("删除失败")
ctx.redirect("/");
}
}
})
app
.use(router.routes())//启动路由
.use(router.allowedMethods());
app.listen(3008);