1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import express from "express" import mongoose from "mongoose" import cors from "cors"
const app = express() app.use(express.json()) app.use(cors())
try { await mongoose.connect("mongodb://127.0.0.1:27017/mongodb-test") } catch (error) { console.error("error:数据库连接失败\n", error) }
const Article = mongoose.model( "Article", new mongoose.Schema({ title: { type: String }, }) )
app.get("/articles", async (req, res) => { const article = await Article.find() res.send({ success: true, message: "get article list", data: article, }) })
app.get("/articles/:id", async (req, res) => { const id = req.params.id const article = await Article.findById(id) res.send({ success: true, message: "get article by id", data: article, }) })
app.post("/articles", async (req, res) => { const body = req.body
const article = await Article.create({ title: body.title, })
res.send({ success: true, message: "create article", data: article, }) })
app.put("/articles/:id", async (req, res) => { const id = req.params.id const body = req.body
const article = await Article.findById(id) article.title = body.title await article.save()
res.send({ success: true, message: "update article", data: article, }) })
app.delete("/articles/:id", async (req, res) => { const id = req.params.id await Article.deleteOne({ _id: id }) res.send({ success: true, message: "delete article", }) })
const port = 3000 app.listen(port, () => { console.log(`http://localhost:${port}`) })
|