当前位置:网站首页>NoSQL mongodb - 04 mongodb database and web service combination case
NoSQL mongodb - 04 mongodb database and web service combination case
2022-06-26 12:35:00 【Preserved egg is very white】
Case study 1: stay Nodejs In the operation MongoDB
MongoDB The authorities provide a lot drive (Drivers) Used to operate MongoDB.
These drivers include almost all major back-end languages , In fact, it is the package corresponding to each platform , Used to connect operations MongoDB.
Here's a simple Node.js operation MongoDB The case of , Reference resources :MongoDB Node Driver — Node.js
Please guarantee MongoDB The service is on .
Initialize the sample project
mkdir node-mongodb-demo
cd node-mongdb-demo
npm init -y
# mongodb It's official Node.js Lower operation MongoDB The toolkit
npm i mongodb
Connect MongoDB
const {
MongoClient } = require('mongodb')
// Create a client instance that connects to the database
const client = new MongoClient('mongodb://127.0.0.1:27017')
async function run() {
try {
// Connect the client to the database service
await client.connect()
// Connect test database
const testDb = client.db('test')
// obtain inventory aggregate
const inventoryCollection = testDb.collection('inventory')
// Query the document
const ret = await inventoryCollection.find()
// find Method returns a pointer to the management query result , You can use toArray() Method traversal view
console.log(await ret.toArray())
} catch (err) {
// The connection fails
console.log(' The connection fails ')
} finally {
// Make sure that / When an error occurs, the client will close the connection
await client.close()
}
}
run()
CRUD operation
On every platform CRUD Operation methods can be found in official documents MongoDB CRUD Operations Find , Switch... In the page “Select your language” Choose the language to use .
create documents
const ret = await inventoryCollection.insertOne({
item: 'card', qty: 15 })
console.log(ret)
Query the document
const ret = await inventoryCollection.find({
item: 'card' })
console.log(await ret.toArray())
const ret = await inventoryCollection.findOne({
item: 'card' })
console.log(ret)
Modify the document
const ret = await inventoryCollection.updateOne(
{
item: 'card'
},
{
$set: {
qty: 100
}
}
)
console.log(ret)
Delete the document
The following example uses _id Match the document to be deleted , By default _id yes ObjectId object , Need to use ObjectId Class to create an instance .
Be careful :MongoDB Previous versions used the name
ObjectIDMethods , Now the name has been discarded , Recommend and change toObjectId.
const {
ObjectId } = require('mongodb')
await inventoryCollection.deleteOne({
_id: ObjectId('61b691a3db3aa35bcac3f440')
})
Case study 2:MongoDB Database integration Web service
Case introduction

This example sets up a support MongoDB database CRUD Operation of the Web Interface services , Used to manage blog posts .
Interface design
This example interface is based on RESTful The interface specification , Reference resources :
This example interface data format :application/json
This example USES postman Debug test interface .
Create articles
- Request path :
POST/articles - Request parameters :Body
- title
- description
- body
- tagList
Request body example :
{
"article": {
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "You have to believe",
"tagList": ["reactjs", "angularjs", "dragons"]
}
}
Sample response data :
- Status code :201
- The response data :
{
"article": {
"_id": 123,
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "It takes a Jacobian",
"tagList": ["dragons", "training"]
}
}
Get article list
- Request path :
GET/articles - Request parameters :Query
- _page: Page number
- _size: The size of each page
Sample response data :
- Status code :200
- The response data :
{
"articles":[{
"_id": "how-to-train-your-dragon",
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "It takes a Jacobian",
"tagList": ["dragons", "training"],
"createdAt": "2016-02-18T03:22:56.637Z",
"updatedAt": "2016-02-18T03:48:35.824Z"
}, {
"_id": "how-to-train-your-dragon-2",
"title": "How to train your dragon 2",
"description": "So toothless",
"body": "It a dragon",
"tagList": ["dragons", "training"],
"createdAt": "2016-02-18T03:22:56.637Z",
"updatedAt": "2016-02-18T03:48:35.824Z"
}],
"articlesCount": 2
}
Get a single article
- Request path :
GET/articles/:id
Sample response data :
- Status code :200
- The response data :
{
"article": {
"_id": "dsa7dsa",
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "It takes a Jacobian",
"tagList": ["dragons", "training"],
"createdAt": "2016-02-18T03:22:56.637Z",
"updatedAt": "2016-02-18T03:48:35.824Z"
}
}
Update article
- Request path :
PATCH/articles/:id - Request parameters :Body
- title
- description
- body
- tagList
Request body example :
{
"article": {
"title": "Did you train your dragon?"
}
}
Sample response data :
- Status code :201
- The response data :
{
"article": {
"_id": 123,
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "It takes a Jacobian",
"tagList": ["dragons", "training"],
"createdAt": "2016-02-18T03:22:56.637Z",
"updatedAt": "2016-02-18T03:48:35.824Z"
}
}
Delete articles
- Request path :
DELETE/articles/:id
Sample response data :
- Status code :204
Initialize project
mkdir article-end
cd article-end
npm init -y
npm i express mongodb
Create an entry file app.js:
// app.js
const express = require('express')
const app = express()
// Configure parsing request body data application/json
// The middleware will put the parsed request body data into req.body
app.use(express.json())
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log('app listenning at port 3000.')
})
Start the service :
# Global installation is recommended nodemon Used to start services
npm i -g nodemon
# Start the service
nodemon app.js
Routing configuration
// app.js
const express = require('express')
const app = express()
// Configure parsing request body data application/json
// The middleware will put the parsed request body data into req.body
app.use(express.json())
app.get('/', (req, res) => {
res.send('Hello World!')
})
// Create articles
app.post('/articles', (req, res) => {
res.send('post /articles')
})
// Get article list
app.get('/articles', (req, res) => {
res.send('get /articles')
})
// Get a single article
app.get('/articles/:id', (req, res) => {
res.send('get /articles/:id')
})
// Update article
app.patch('/articles/:id', (req, res) => {
res.send('patch /articles/:id')
})
// Delete articles
app.delete('/articles/:id', (req, res) => {
res.send('delete /articles/:id')
})
app.listen(3000, () => {
console.log('app listenning at port 3000.')
})
Create articles
// app.js
const express = require('express')
// database
const {
MongoClient } = require('mongodb')
const connectUri = 'mongodb://localhost:27017'
const dbClient = new MongoClient(connectUri)
//...
// Create articles
app.post('/articles', async (req, res) => {
try {
// 1. Get client form data
const {
article } = req.body
// 2. data validation
if (!article || !article.title || !article.description || !article.body) {
return res.status(422).json({
error: ' The request parameter does not meet the rule requirements '
})
}
// 3. Insert the verified data into the database
await dbClient.connect()
const collection = dbClient.db('test').collection('articles')
const ret = await collection.insertOne(article)
article._id = ret.insertedId
// 4. Send successfully / Failure response
res.status(201).json(article)
} catch (err) {
res.status(500).json({
error: err.message
})
}
})
//...
Unified processing of server errors
//...
// Create articles
app.post('/articles', async (req, res, next) => {
try {
//...
} catch (err) {
// The error handling middleware will handle it uniformly
next(err)
}
})
//...
// Error handling middleware
// Before that, all routes call next(err) Will enter here
// Be careful : Must have 4 Parameters will be identified as error handling middleware
app.use((err, req, res, next) => {
res.status(500).json({
error: err.message
})
})
app.listen(3000, () => {
console.log('app listenning at port 3000.')
})
Get article list
// Get article list
app.get('/articles', async (req, res, next) => {
try {
let {
_page = 1, _size = 10 } = req.query
_page = parseInt(_page)
_size = parseInt(_size)
await dbClient.connect()
const collection = dbClient.db('test').collection('articles')
const ret = await collection
.find() // Query data ( To obtain the cursor )
.skip((_page - 1) * _size) // How many
.limit(_size) // How many
const articles = await ret.toArray()
const articlesCount = await collection.countDocuments()
res.status(200).json({
articles,
articlesCount
})
} catch (err) {
next(err)
}
})
Get article details
// introduce ObjectId Method
const {
MongoClient, ObjectId } = require('mongodb')
//...
// Get a single article
app.get('/articles/:id', async (req, res, next) => {
try {
await dbClient.connect()
const collection = dbClient.db('test').collection('articles')
const article = await collection.findOne({
_id: ObjectId(req.params.id) })
res.status(200).json({
article
})
} catch (err) {
next(err)
}
})
Update article
// Update article
app.patch('/articles/:id', async (req, res, next) => {
try {
await dbClient.connect()
const collection = dbClient.db('test').collection('articles')
const article = await collection.updateOne(
{
_id: ObjectId(req.params.id) },
{
$set: req.body.article
}
)
// req.body.article After the update, the status information of the update result will be changed
// Query the updated data ( Match only _id It can be abbreviated as "pass parameter" )
const ret = await collection.findOne(ObjectId(req.params.id))
res.status(201).json(ret)
} catch (err) {
next(err)
}
})
Delete articles
// Delete articles
app.delete('/articles/:id', async (req, res, next) => {
try {
await dbClient.connect()
const collection = dbClient.db('test').collection('articles')
const article = await collection.deleteOne({
_id: ObjectId(req.params.id) })
res.status(204).json({
})
} catch (err) {
next(err)
}
})
边栏推荐
- PHP uses laravel pay component to quickly access wechat jsapi payment (wechat official account payment)
- I want to know whether flush is a stock market? Is online account opening safe?
- 由错误<note: candidate expects 1 argument, 0 provided>引发的思考
- 2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
- File decryption in webgame development
- Why is password salt called "salt"? [Close] - why is a password salt called a "salt"? [closed]
- SQL injection in Pikachu shooting range
- Question B of 2016 Sichuan Ti Cup Electronic Design Competition
- Oracle lock table query and unlocking method
- Basic principle of MOS tube and important knowledge points of single chip microcomputer
猜你喜欢

Spark-day03-core programming RDD operator
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

Scala-day03- operators and loop control

Several rare but useful JS techniques

手把手带你学会Odoo OWL组件开发(7):OWL项目实战使用

Mongodb of NoSQL - 03 mongodb CRUD

International beauty industry giants bet on China

Build Pikachu shooting range and introduction

Scala-day06- pattern matching - Generic

环形队列php
随机推荐
程序员必备,一款让你提高工作效率N倍的神器uTools
7-3 最低通行费
UDP协议详解[通俗易懂]
Configuring Apache digest authentication
详细实操分享,下班刷了两小时的搞笑视频,一个月收益7000多
2016年四川省TI杯电子设计竞赛B题
手把手带你学会Odoo OWL组件开发(7):OWL项目实战使用
Consumer goods enterprises, four pain points of member marketing
fastjson的JSONArray和JSONObject[通俗易懂]
Example of parameter passing from laravel query constructor to closure method
Precautions for opening a securities account is it safe to open an account
Thinkphp5 query report: sqlstate[hy093]: invalid parameter number
MS17_ 010 utilization summary
[solved] data duplication or data loss after laravel paginate() paging
[graduation season · advanced technology Er] I remember the year after graduation
How can we reach members more effectively?
Spark-day02-core programming-rdd
Cross platform members get through the two channels of brand Ren Du
Report on in-depth analysis and investment strategy recommendations for China's petroleum coke industry (2022 Edition)
How long ago did PHP get