MongoDB干货学习-增删改查

1,513 阅读3分钟

MongoDB

一、基础

1. 环境配置

首先安装 MongoDB 和 Node.js

npm安装mongoose

elegant mongodb object modeling for node.js mongoose可以理解为在node中可以连接mongoDB数据库的工具

npm install mongoose --save

2. 简单使用

在js文件中引入mongoose,并和数据库建立连接

// server.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test')

假设我们有多个产品,想要在数据库中记录每个产品,每个产品有一个tittle属性

// server.js 
// 定义产品模型
const Product = mongoose.model('Product', new mongoose.Schema({
  title: String,
}))

为了测试,使用insertMany方法向数据库中插入多条数据,注意该方法只执行一次后就需要注释掉,一直执行会一直插入数据

// server.js
// Product.insertMany([
//   {title: '产品1'},
//   {title: '产品2'},
//   {title: '产品3'},
// ])

使用find方法查询数据库中的所有数据

// server.js
app.get('/products', async function(req, res){
  res.send(await Product.find())
})

完整代码为

const express = require('express');

const app = express();

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test')
// 定义产品模型
const Product = mongoose.model('Product', new mongoose.Schema({
  title: String,
}))

// Product.insertMany([
//   {title: '产品1'},
//   {title: '产品2'},
//   {title: '产品3'},
// ])


app.get('/', function(req, res){
  res.send({ page: 'home' })
})

app.get('/about', function(req, res){
  res.send({ page: 'About Us' })
})

app.get('/products', async function(req, res){
  res.send(await Product.find())
})

app.listen(3000, () => {
  console.log('App listening on port 3000!');
})

结果 image.png

二、查询

1. 产品列表页接口

查询全部数据

/**
 * find 查询全部数据
 */
app.get('/products', async function(req, res){
  const data = await Product.find();
  res.send(data)
})

分页场景

/**
 * skip(num) 跳过多少
 * limit(num) 限制返回数据条数
 * skip和limit结合起来可用于分页
 */
app.get('/products', async function(req, res){
    const data = await Product.find().skip(1).limit(2);
    res.send(data)
})

指定查询条件

/**
* where 指定查询条件
*/
app.get('/products', async function(req, res){
    const data = await Product.find().where({
        title: '产品2'
    });
    res.send(data)
})

排序

/**
* sort 排序 1:正序 -1:倒序
*/
app.get('/products', async function(req, res){
    const data = await Product.find().sort({_id: -1})
    res.send(data)
})

2. 产品详情页接口

/**
* findById 查询结果就是一个对象,不再是数组
*/
app.get('/products/:id', async function(req, res){
  const data = await Product.findById(req.params.id);
  res.send(data);
})

三、新增和POST请求

假设我们想要新录入一条产品数据,如何写一个录入产品数据的接口呢?

1. REST Client插件

在Vscode中安装REST Client插件,这个插件可以用代码的方式发起各种HTTP请求

image.png

在根目录新建一个文件, 后缀名为http, 比如test.http

  • 文件中写入请求代码,点击Send Request, 右侧能看到请求结果
  • 每个请求需要用###分开
  • 可以使用@定义变量 {{}}引用变量

image.png

2. POST请求

test.http文件中写入

POST {{uri}}products
Content-Type: application/json

{
  "title": "产品4"
}

3. 产品录入接口

server.js文件中写入

app.post('/products', async function(req, res){
  const data = req.body; // POST请求提交的数据
  const product = await Product.create(data); // 创建产品
  res.send(product); // 将产品数据发送出去
})

因为POST请求发送的是json数据,所以在server.js文件中需要写入

// 允许express处理提交过来的json数据
app.use(express.json())

点击录入产品请求的Send Request,获得一条产品数据 image.png 点击产品列表请求的Send Request,发现产品数据已成功录入 image.png

四、修改和PUT请求

如果我们想要修改某一条产品数据,例如产品title,如何写一条修改产品数据接口?

server.js文件中

/**
*修改产品数据接口
*/
app.put('/products/:id', async function(req, res){
  // 查找
  const product = await Product.findById(req.params.id);
  // 赋值
  product.title = res.body.title;
  // 保存
  await product.save();
  // 返回
  res.send(product);
})

test.http文件中写入

PUT {{uri}}products/61372a06cc69aac0beb6c606
Content-Type: application/json

{
  "title": "产品5_修改"
}

点击Send Request, 发送修改产品请求,将产品5的title修改为"产品5_修改" image.png

五、删除和DELETE请求

server.js文件中写删除产品数据接口

app.delete('/products/:id', async function(req, res){
  // 查找
  const product = await Product.findById(req.params.id);
  // 删除
  await product.remove();
  // 返回一个状态,表示执行成功
  res.send({
    success: true
  });
})

test.http文件中写入

DELETE {{uri}}products/61372a06cc69aac0beb6c606

点击Send Request, 发送请求删除产品5,执行结果为 image.png