当前位置:网站首页>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 !
边栏推荐
- Mathematics in machine learning -- point estimation (IV): maximum posteriori probability (map)
- MySQL date timestamp conversion
- Funny! Pictures and texts give you a comprehensive understanding of the effects of dynamics and mass
- Use Google search like a professional
- National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
- Global and Chinese market of inverted syrup 2022-2028: Research Report on technology, participants, trends, market size and share
- Virtual machine virtual disk recovery case tutorial
- 嵌入式开发基础之线程间通信
- Handling of communication failure between kuberbetes pod
- Page scrolling effect library, a little skinny
猜你喜欢

C. K-th not divisible by n (Mathematics + thinking) codeforces round 640 (Div. 4)
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization

Applet wxss

Ps\ai and other design software pondering notes

Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)

ZOJ - 4104 sequence in the pocket
MySQL Advanced Series: locks - locks in InnoDB

Ui- first lesson

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

A survey of training on graphs: taxonomy, methods, and Applications
随机推荐
National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
Factory mode
Understanding of deep separable convolution, block convolution, extended convolution, transposed convolution (deconvolution)
How does easydss, an online classroom / online medical live on demand platform, separate audio and video data?
对深度可分离卷积、分组卷积、扩张卷积、转置卷积(反卷积)的理解
MySQL進階系列:鎖-InnoDB中鎖的情况
Goby+AWVS 实现攻击面检测
Little red book, hovering on the edge of listing
Global and Chinese market for commercial barbecue smokers 2022-2028: Research Report on technology, participants, trends, market size and share
B. Terry sequence (thinking + greed) codeforces round 665 (Div. 2)
Object store signature generation
[golang] Introduction to golang (I) establishment of running environment
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?
Global and Chinese market of insect proof clothing 2022-2028: Research Report on technology, participants, trends, market size and share
Script design for automatic login and command return
What does the router pin mean?
Use Google search like a professional
Global and Chinese markets of natural insect repellents 2022-2028: Research Report on technology, participants, trends, market size and share
A survey of training on graphs: taxonomy, methods, and Applications
ThinkPHP vulnerability exploitation tool