当前位置:网站首页>Introduction to koa (IV) koa operation database
Introduction to koa (IV) koa operation database
2022-06-24 16:37:00 【Uncertainty】
1 NoSql brief introduction
We use koa The development of the background , The most commonly used database is mongodb, This is a NoSql A type of database , What is NoSql Well ? The first thing to say is ,NoSql It doesn't mean NO SQL No, SQL It means . actually , It is Not Only SQL Abbreviation . It means : Use relational database when it is applicable to relational database , It is not necessary to use relational database when it is not applicable , Consider using a more appropriate data store .
Tables in relational databases store structured data , The field groups of each record are the same , Even if not all fields are required for every record , But the database assigns all the fields to each data . Instead of relational databases, key value pairs (key-value) Storage , Its structure is not fixed , Each record can have a different key , Each record can add its own key value pairs as needed , This will not be limited to fixed structures , It can reduce the cost of time and space .
1.1 NoSql Advantages and disadvantages of database
- The advantages are mainly reflected in the following points :
- Simple extension
- Read and write quickly
- Low cost
- Flexible data model
- In terms of deficiencies, there are mainly the following points :
- Don't offer right SQL Support for
- The supported features are not rich enough
- The existing products are not mature enough
2 Mongoodb
MongoDB Use C++ Non relational database written in language . Features are high performance 、 Easy to deploy 、 Easy to use , It is very convenient to store data .
2.1 The main features
- For collection storage , Easy to store object type data
- Model freedom
- Support dynamic query
- Support full indexing , Contains internal objects
- Support for replication and recovery
- Use efficient binary data storage , Include large objects
- The file storage format is
BSON( A kind ofJSONAn extension of )
3 Mongodb install
There are two ways to install
3.1 Mongodb Atlas
A kind of It's using mongodb atlas, The official website has been registered , Direct local connection is OK . The disadvantage is the need for civilized Internet access , It is usually very slow to connect . Registered address , The tutorial can refer to here
Another kind Is installed locally ( My is windows10, Local fast ), Direct installation msi, Connect directly after startup , You can search and install on the Internet by yourself . Download address
4 Koa + Mongodb operation
4.1 Install Links
npm i mongoose -Sconst mongoose = require('mongoose') // Default 27017 port mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }, () => console.log(' Database connection successful ')) mongoose.connection.on('error', console.error) Like link address 、 We'd better put the port configuration in the configuration file separately , Better maintenance // app/config.js module.exports = { connectionStr: 'mongodb://localhost:27017/test' }- stay
app/index.jsintroduce - start-up
mongoodbservice
- start-up
Koaservice
You can see koa Linking database succeeded
4.2 establish user modal
- newly build
app/models/user.js( Use the plural ), Build a model const mongoose = require('mongoose') const { Schema, model } = mongoose // adopt schema Design the table structure , Simple structure and complex structure can , Each one is automatically created _id const userSchema = new Schema({ name: { type: String, required: true // necessary }, password: { type: String, required: true } }) // User surface module.exports = model('User', userSchema) - Operate the database to realize the function of adding, deleting, modifying and querying
Introduce the model we created into the controller created in the previous section
const User = require('../models/user')
class UsersCtl {
// Get the list of users
async find(ctx) {
// Operating the database must await
ctx.body = await User.find()
}
// according to id Find a user
async findById(ctx) {
ctx.body = await User.findById(ctx.params.id)
}
// Create user
async create(ctx) {
ctx.body = await new User(ctx.request.body).save()
}
// Update user information
async update(ctx) {
const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
ctx.body = user
}
// Delete user
async delete(ctx) {
const user = await User.findByIdAndRemove(ctx.params.id)
ctx.body = user
}
}
module.exports = new UsersCtl() We first add new users and then get and delete them , Convenient test , Use postman Test the following :
increase :
To obtain a list of :
Get sb :
Delete sb :
Update user information :
4.3 Optimize logic
We must judge the correctness of the data before operating the database , For example, to determine whether a duplicate name has been added , Modify to determine whether this user exists , Some operations also require authentication .
- Use
koa-parameterCheck the parametersnpm i koa-parameter -Sapp/index.js ... const parameter = require('koa-parameter') ... // Verify the of the request body , Put it in the back app.use(parameter(app)) // Context ctx Add... Methods , Global verification - Add / delete / modify query / add judgment You can use it yourself
postmanTest the following code const User = require('../models/user') class UsersCtl { // Get the list of users async find(ctx) { // Operating the database must await ctx.body = await User.find() } // according to id Find a user async findById(ctx) { const user = await User.findById(ctx.params.id) if (!user) { ctx.throw(404, ' The user doesn't exist ') } else { ctx.body = user } } // Create user async create(ctx) { // Intermediate database global method verification parameters ctx.verifyParams({ name: { type: 'string', required: true }, password: { type: 'string', required: true } }) // Determine whether the user name already exists in the library const { name } = ctx.request.body const user = await User.findOne({ name }) if (user) { ctx.throw(409, ' User name already exists ') } ctx.body = await new User(ctx.request.body).save() } // Update user information async update(ctx) { ctx.verifyParams({ name: { type: 'string', required: true }, password: { type: 'string', required: true } }) const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body) if (!user) { ctx.throw(404, ' The user doesn't exist ') } ctx.body = user } // Delete user async delete(ctx) { const user = await User.findByIdAndRemove(ctx.params.id) // After deleting , Will first return the original if (!user) { ctx.throw(404, ' The user doesn't exist ') } ctx.body = user } } module.exports = new UsersCtl()
5 mongoodb Other operating
- We see the return password field in the list , This is not appropriate , Easy to leak , So you need to hide it in the model . If necessary, it can be used in table lookup
selectkeyword password: { type: String, required: true, select: false // Will not return } await User.find().select(‘+password’) Usually useKoaWill be used on the front endfieldsField , The background returns the front-end incoming format of the hidden field through this field :password;name;age, ? Splicing url Back // Get the list of users async find(ctx) { const { fields = '' } = ctx.query const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('') // Operating the database must await ctx.body = await User.find().select(selectFields) }async find(ctx) { let { fields = '', page = 1, limit = 10 } = ctx.query const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('') // page and limit Cannot be less than or equal to 0 page = Math.max(+page, 1) - 1 // page Front end from 1 Start , Backstage from 0 Start limit = Math.max(+limit, 10) // Operating the database must await ctx.body = await User.find().limit(limit).skip(page * limit).select(selectFields) } - If there are too many lists , We need to use paging to find
mongoodbProvideslimit skipField - Lists use fuzzy search , A regular fix cosnt { q = '' } = ctx.query await User.find({ name: new RegExp(q) // Fuzzy search }) What if multiple fields are searched ?await User.find({ $or: [{title: q}, {name: q}] })
- Use reference association table Focus on user functions , User module adds fields // Getting the list will automatically return following Field following: { type: [ { type: Schema.Types.ObjectId, // Use _id relation ref: 'User' // Quote to User surface } ] } Focus on the controller // Focus on async follow(ctx) { // Get yourself ( You need to log in normally , from ctx.state.user._id obtain ) const ownUser = await User.findById(ctx.params.my_id) // mongoose The type of data that comes with it , Use toString() Method if (!ownUser.following.map(id => id.toString()).includes(ctx.params.id)) { ownUser.following.push(ctx.params.id) ownUser.save() } ctx.status = 204 } Use put Method register route router.put('/following/:my_id/:id', follow) Use
postmanPull list after request
If you want to get the details of your followers, use populate keyword :
ctx.body = await User.find({
name: new RegExp(q) // Fuzzy search
}).limit(limit).skip(page * limit).select(selectFields).populate('following') After that, I want to write down some practical examples , A small program or pc(vue3) With Koa, But I didn't think about what to do , Interested friends can leave messages on the backstage of the official account .
If it helps you , Welcome to share with friends ! Thank you for reading !
边栏推荐
- 6 things all engineers should know before FEA
- ThinkPHP vulnerability exploitation tool
- A memory leak caused by timeout scheduling of context and goroutine implementation
- How to use the national standard streaming media server to view the video stream of the surveillance camera? How to correctly use UDP and TCP protocols?
- Tencent releases the full platform version of reasoning framework TNN, and supports mobile terminal, desktop terminal and server terminal at the same time
- Goby+awvs realize attack surface detection
- MySQL進階系列:鎖-InnoDB中鎖的情况
- Applet wxss
- Inter thread communication of embedded development foundation
- MySQL Advanced Series: locks - locks in InnoDB
猜你喜欢

C. K-th Not Divisible by n(数学+思维) Codeforces Round #640 (Div. 4)

B. Ternary Sequence(思维+贪心)Codeforces Round #665 (Div. 2)

A survey on model compression for natural language processing (NLP model compression overview)

C. Three displays codeforces round 485 (Div. 2)
![[go] concurrent programming channel](/img/6a/d62678467bbc6dfb6a50ae42bacc96.jpg)
[go] concurrent programming channel

Some adventurer hybrid versions with potential safety hazards will be recalled

Problems encountered in the work of product manager

A survey of training on graphs: taxonomy, methods, and Applications

Applet - use of template

Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)
随机推荐
【prometheus】1. Monitoring overview
How do HPE servers make RAID5 arrays? Teach you step by step today!
Video structured intelligent analysis platform easycvr video recording plan function optimization / regularly delete expired videos
Transpose convolution explanation
转置卷积详解
Leetcode notes of Google boss | necessary for school recruitment!
National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
How does easydss, an online classroom / online medical live on demand platform, separate audio and video data?
06. Tencent cloud IOT device side learning - Introduction to basic functions
How to pop up an alarm through the national standard gb28181 protocol video platform easygbs for mobile detection / perimeter intrusion detection video recording
Pytorch transpose convolution
Ps\ai and other design software pondering notes
Global and Chinese markets of stainless steel barbecue ovens 2022-2028: Research Report on technology, participants, trends, market size and share
Tencent releases the full platform version of reasoning framework TNN, and supports mobile terminal, desktop terminal and server terminal at the same time
[play with Tencent cloud] my operation strategy from domain name application to website filing in Tencent cloud
国泰君安期货安全么?期货开户怎么开?期货手续费怎么降低?
Handling of communication failure between kuberbetes pod
Heavy release! Tencent cloud ASW workflow, visual orchestration cloud service
Introduction of thread pool and sharing of practice cases
A survey on dynamic neural networks for natural language processing, University of California