文章目录
- 连接
- 查
- 增
- 删
- 改
连接
const { MongoClient, ObjectId } = require("mongodb");
const MongoClientConfig = {
useUnifiedTopology: true,
auth: {
user: "xxx",
password: "xxx",
},
};
const url = `mongodb://${options.host}:${options.port}/${options.db_name}`;
const client = new MongoClient(url, MongoClientConfig);
client.connect(async err => {
if (err) return;
console.log("OK!👏");
});
查
app.get("/getTodoLists", async (req, res) => {
const result = await client.db().collection("todoList").find().toArray();
console.log("result:", result);
res.send(result);
});
增
app.post("/addTodo", (req, res) => {
let params = "";
req.on("data", data => {
params += data;
});
req.on("end", async () => {
const { content, reminderTime } = JSON.parse(params);
const data = {
content,
status: false,
reminderTime: new Date(reminderTime),
};
try {
const {
ops: [todo],
} = await client.db().collection("todoList").insertOne(data);
console.log(todo);
res.send(todo);
} catch (error) {
console.error("addTodo:", error);
res.status(500);
}
});
});
删
app.post("/deleteTodoItem", (req, res) => {
let params = "";
req.on("data", data => {
params += data;
});
req.on("end", () => {
const { id } = JSON.parse(params);
client
.db()
.collection("todoList")
.deleteOne({ _id: ObjectId(id) }, (err, result) => {
if (err) res.status(500);
console.log("delete success:", result);
res.send("ok");
});
});
});
改
app.post("/toggleTodoState", (req, res) => {
let params = "";
req.on("data", data => {
params += data;
});
req.on("end", () => {
const { id, status } = JSON.parse(params);
console.log(id, status);
client
.db()
.collection("todoList")
.updateOne({ _id: ObjectId(id) }, { $set: { status } }, (err, result) => {
if (err) res.status(500);
if (result.result.n === 1) {
res.send("ok");
}
});
});
});