-index.js
const Koa = require("koa"),
Router = require("koa-router"),
path = require("path"),
render = require("koa-art-template"),
bodyParser = require("koa-bodyparser"),
DB = require("./module/db");
const COLLECTION_NAME = "teacher";
const app = new Koa();
const router = new Router();
app.use(bodyParser());
render(app, {
root: path.join(__dirname, "views"),
extname: ".html",
debug: true
});
router.get("/", async ctx => {
let docs = await DB.find(COLLECTION_NAME);
await ctx.render("index", { docs });
});
router.get("/addUser", async ctx => {
await ctx.render("addUser");
});
router.post("/add", async ctx => {
let {
result: { n, ok }
} = await DB.insert(COLLECTION_NAME, ctx.request.body);
if (ok) {
ctx.redirect("/");
}
});
router.get("/edit", async ctx => {
let { id } = ctx.query;
let [docs] = await DB.find(COLLECTION_NAME, { _id: DB.getObjectId(id) });
await ctx.render("edit", { docs });
});
router.post("/doEdit", async ctx => {
let { _id, ...obj } = ctx.request.body;
let {
result: { n, ok }
} = await DB.updateOne(COLLECTION_NAME, { _id: DB.getObjectId(_id) }, obj);
if (ok) {
ctx.redirect("/");
}
});
router.get("/del", async ctx => {
let { id } = ctx.query;
let {
result: { n, ok }
} = await DB.removeOne(COLLECTION_NAME, { _id: DB.getObjectId(id) });
if (ok) {
ctx.redirect("/");
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8080);
- module/db.js
const config = require("./config");
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;
const client = new MongoClient(config.dbUrl, { useUnifiedTopology: true });
class Db {
static getInstance() {
if (!Db.instance) {
Db.instance = new Db();
}
return Db.instance;
}
constructor() {
this.dbClient = "";
this.connect();
}
connect() {
return new Promise((resolve, reject) => {
if (!this.dbClient) {
client.connect(err => {
if (err) {
reject(err);
} else {
this.dbClient = client.db(config.dbName);
resolve(this.dbClient);
}
});
} else {
resolve(this.dbClient);
}
});
}
find(collectionName = "student", json = {}) {
return new Promise((resolve, reject) => {
this.connect().then(db => {
db.collection(collectionName)
.find(json)
.toArray((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
});
}
update() {}
insertMany(collectionName, insertArr) {
return new Promise((resolve, reject) => {
this.connect().then(db => {
db.collection(collectionName).insertMany(insertArr, (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);
} else {
resolve(result);
}
});
});
});
}
updateOne(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);
}
}
);
});
});
}
removeOne(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect().then(db => {
db.collection(collectionName).deleteOne(json, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
});
}
getObjectId(id) {
return ObjectId(id);
}
}
module.exports = Db.getInstance();
新增了一个设置ObjectId的方法
- module/config.js
// 配置文件
const app = {
dbUrl: "mongodb://localhost:27017",
dbName: "student"
};
module.exports = app;
-index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div><a href="./addUser">新增用户</a></div>
<table border="1" width="100%" cellpadding="0" cellspacing="0">
<tr>
<th>姓名</th>
<th>年纪</th>
<th>操作</td>
</tr>
{{each docs}}
<tr align="center">
<td>
{{$value.name}}
</td>
<td>
{{$value.age}}
</td>
<td>
<span><a href="/edit?id={{@ $value._id}}">修改</a></span>
<span><a href="/del?id={{@ $value._id}}">删除</a></span>
</td>
{{/each}}
</tr>
</table>
</body>
<script>
</script>
</html>
- edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<p>编辑用户</p>
<form action="/doEdit" method="post" id="form">
<input type="hidden" name="_id" value="{{@ docs._id}}" />
<p>用户名:<input type="text" name="name" value="{{docs.name}}" /></p>
<p>年纪:<input type="text" name="age" value="{{docs.age}}" /></p>
<p><input type="submit" value="提交" /></p>
</form>
</body>
</html>
- addUser.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>新增用户</h1>
<form action="/add" method="post" id="form">
<p>用户名:<input type="text" name="name" /></p>
<p>年纪:<input type="text" name="age" /></p>
<p><input type="submit" value="提交" /></p>
</form>
</body>
</html>
网友评论