MongoDB
一、基础
1. 环境配置
npm安装mongoose
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!');
})
复制代码
结果
二、查询
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请求
在根目录新建一个文件, 后缀名为http
, 比如test.http
- 文件中写入请求代码,点击Send Request, 右侧能看到请求结果
- 每个请求需要用
###
分开 - 可以使用
@
定义变量{{}}
引用变量
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,获得一条产品数据
点击产品列表请求的Send Request,发现产品数据已成功录入
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END