mongodb快速使用

mongodb快速使用

安装

mongodb 官网mongodb 中文官网

node 实例: 使用 express 和 mongoose 实现简单的文章管理 API

初始化项目

bash
npm init -y

依赖安装

bash
npm i express@latest cors mongoose

数据建模

js
import mongoose from "mongoose"

const Article = mongoose.model(
    "Article",
    new mongoose.Schema({
        title: { type: String },
    })
)

增删改查 API 实现

获取列表

js
app.get("/articles", async (req, res) => {
    const article = await Article.find()
    res.send({
        success: true,
        message: "get article list",
        data: article,
    })
})

根据 id 获取详情

js
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,
    })
})

创建文章

js
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,
    })
})

编辑文章

js
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,
    })
})

删除文章

js
app.delete("/articles/:id", async (req, res) => {
    const id = req.params.id
    await Article.deleteOne({ _id: id })

    // 或者可以使用以下方法进行删除
    // const article = await Article.findById(id)
    // await article.remove()

    res.send({
        success: true,
        message: "delete article",
    })
})

完整代码

查看运行情况

可以使用 vscode 插件 rest client 来测试接口运行情况,以下是我本地接口测试文件。如果你要在本地测试,可以将 66ae4047563fa3933c1b38ba 改成真实的查询列表里的某一个文章的 id 即可

提醒

rest client 这个插件在我的博客里有介绍,可以移步 rest client 插件使用 了解其基础使用方法

测试代码

发布订阅模式
近况说明

评论区

评论加载中...