mongodb可视化工具
robomongo
接口测试
vscode中可以安装插件rest client
rest client使用:在根目录下新建后缀名为http的文件,每个请求路径用###分开
也可以自行下载postman
数据库连接
在node中使用mongodb需要用到mongoose
安装mongoose
npm i mongoose
const express = require('express')
const app = express() //返回一个应用实例
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/数据库名字')
//需要定义模型(类似表)一般大写
const Product = mongoose.model('Product ',new mongoose.Schema({
title:String,
}))
app.get('/products',async(req,rea) => {
//每一次的查询都是异步操作
res.send(await Produce.find())
})
//开启监听器
app.listen(3000,() => {
console.log('ok..')
})
增加
Model.create(doc(s),[callback])
app.post('/categories', async (req, res) => {
const model = await Category.create(req.body)
res.send(model)
})
删除
Model.remove(conditions, [callback])
Model.findByIdAndRemove(id, [options], [callback])
//删除
app.delete('/categories/:id', async (req, res) => {
await Category.findByIdAndRemove(req.params.id)
res.send('删除成功')
})
修改
Model.update(conditions, doc, [options], [callback])
Model.findByIdAndUpdate(id, doc, [options], [callback])
//patch是部分修改 put是整个覆盖都可
app.put('/categories/:id', async (req, res) => {
//id参数来自req.params.id
const model = await Category.findByIdAndUpdate(req.params.id,req.body)
//把查到的数据发送给前端
res.send(model)
})
查询
查询多条
Model.find(conditions, [projection], [options], [callback])
- limit():限制查询条数
- skip():跳过几条
通常使用x.find().skip(xx).limitxx()进行分页处理 - where({}):指定查询条件
- sort({}):排序 1为正序 -1为倒序
查询单条
Model.findById(id, [projection], [options], [callback])
app.get('/categories/:id', async (req, res) => {
//id参数来自req.params.id
const data= await Category.findById(req.params.id)
//把查到的数据发送给前端
res.send(data)
})