- 创建文件夹 并在文件夹下运行
npm init -y
- 安装express以及mongodb
npm install --no-audit express --save
npm install --no-audit mongodb --save
npm install --no-audit body-parser --save
- demo
const express = require("express");
const app = express();
const {MongoClient} = require("mongodb");
const url = "mongodb://localhost:27017";
const db = "test";
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.listen(8089);
app.get("/:username",(req,res)=>{
MongoClient.connect(url,{ useUnifiedTopology: true },(error,client)=>{
let username = req.params["username"]
console.log(username);
let dbs = client.db(db);
dbs.collection('uset').find({"username":username}).toArray((err,result)=>{
res.send(result)
});
})
});
app.post("/insert",(req,res)=>{
console.log(req.body);
MongoClient.connect(url,{ useUnifiedTopology: true },(error,client)=>{
let dbs = client.db(db);
dbs.collection('uset').insertOne(req.body);
res.send("success")
})
})
app.delete("/delete/:username",(req,res)=>{
let username = req.params['username'];
MongoClient.connect(url,{ useUnifiedTopology: true },(error,client)=>{
let dbs = client.db(db);
dbs.collection('uset').deleteOne({"username":username},(error,result)=>{
if (error)
res.send(error);
res.send(result);
});
})
})
app.put("/update/:username",(req,res)=>{
let username = req.params['username'];
MongoClient.connect(url,{ useUnifiedTopology: true },(error,client)=>{
let dbs = client.db(db);
dbs.collection('uset').updateMany({"username":username},{$set:{price:101}},(error,result)=>{
if (error)
res.send(error);
res.send(result);
});
})
})