1 no introduction

We use KOA development background, the most commonly used database is mongodb, which is a type of NoSql database, then what is NoSql? First of all, NoSql does not mean NO SQL does not mean SQL. In fact, it stands for Not Only SQL. The meaning is: use a relational database when it is applicable, and there is no need to use a relational database when it is not applicable. Consider using a more appropriate data store.

The tables in a relational database store some structured data, and each record has the same composition of fields. Even though not all fields are required for each record, the database allocates all fields to each data. The non-relational database is stored by key-value pairs. Its structure is not fixed. Each record can have different keys, and each record can add some of its own key-value pairs as required.

1.1 Advantages and Disadvantages of NoSql Databases

  • The advantages are mainly reflected in the following points:

    • Simple extensions
    • Fast reading and writing
    • Low cost
    • Flexible data model
  • The deficiencies mainly include the following points:

    • No support for SQL is provided
    • Not enough features are supported
    • The existing product is not mature enough

2 Mongoodb

MongoDB is a non-relational database written in C++ language. Features: high performance, easy deployment, easy use, and convenient data storage.

2.1 Main Features

  • Collection oriented storage, easy to store object type data
  • Model free
  • Support dynamic query
  • Full index support, including internal objects
  • Supports replication and failover
  • Use efficient binary data storage, including large objects
  • The file storage format isBSON(aJSONThe extension)

3 mongo installation

There are two installation methods

3.1 directing the Atlas

One way is to use mongodb Atlas. After registering on the official website, you can connect directly to the local network. Disadvantage is the need for civilized Internet access, usually connected to the very slow. Register address, tutorial can refer to here

Another kind ofIs the installation to the local (my is Windows10, local fast ah), direct installation OF MSI, after the start of the direct connection, we can be their own online search installation.Download address

4 Koa + Mongodb operations

4.1 Installation Links

  • npm i mongoose -S
  • inapp/index.jsThe introduction of
Const mongoose = the require (' mongoose ') / / the default port 27017 mongoose. Connect (' mongo: / / localhost: 27017 / test ', {useNewUrlParser: true}, () => console.log(' database connected successfully ')) Mongoose.connection. on('error', console.error)Copy the code

Like link address, port configuration we’d better separate in the configuration file, better maintenance

// app/config.js
module.exports = {
  connectionStr: 'mongodb://localhost:27017/test'
}
Copy the code
  • Start themongoodbservice

  • Start theKoaservice

You can see that the KOA database link succeeded

4.2 createuser modal

  • newapp/models/user.js(Plural), build a model
Const mongoose = require('mongoose') const {Schema, model} = mongoose _id const userSchema = new Schema({name: {type: String, required: true // required}, password: {type: String, required: true}}) // User table module.exports = model('User', userSchema)Copy the code
  • Operation database to achieve the function of adding, deleting, changing and checking

Introduce the model we created into the controller we created in the previous section

const User = require('.. /models/user') class UsersCtl {// get user list async find(CTX) {// Operation 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 a User async create(CTX) {ctx.body = Await new User(ctx.request.body).save()} async update(CTX) {const User = await User.findByIdAndUpdate(ctx.params.id, Ctx.request.body) ctx.body = user} async delete(CTX) {const user = await user.findByidAndRemove (ctx.params.id)  ctx.body = user } } module.exports = new UsersCtl()Copy the code

We first add users and then obtain and delete them to facilitate testing. Postman test is as follows:

Add:

Get the list:

Get someone:

Delete someone:

Update user information:

4.3 Optimization Logic

We must judge the correctness of the data before operating the database, for example, increase to judge whether there is a duplicate name, modify to judge whether there is this user, some operations also need authentication and so on.

  • usekoa-parameterVerify parameters

npm i koa-parameter -S

app/index.js ... const parameter = require('koa-parameter') ... App.use (parameter(app)) // context CTX adds a method for global validationCopy the code
  • Add, delete, change, check and add judgment

You can test the following code yourself using Postman

const User = require('.. /models/user') class UsersCtl {// get user list async find(CTX) {// Operation database must await ctx.body = await user.find ()} // according to id Async findById(CTX) {const user = await user.findByid (ctx.params.id) if (! user) { ctx.throw(404, 'User does not exist ')} else {ctx.body = user}} // Create user async create(CTX) {// Intermediate library global method verification parameter ctx.verifyParams({name: {type: 'string', required: true }, password: { type: 'string', required: 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()} 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, Body = user} // Delete user async delete(CTX) {const user = await user.findByidAndRemove (ctx.params.id) // If (! User) {ctx.throw(404, 'user does not exist ')} ctx.body = user}} module.exports = new UsersCtl()Copy the code

5 Mongoodb Perform other operations

  • We see a return password field in the list, which is inappropriate and leaky, so it needs to be hidden in the model. This can be used for table lookup if necessaryselectThe keyword
Password: {type: String, required: true, select: false // will not return} await user.find ().select(' +password ')Copy the code

Typically, Koa uses the fields field in the front end and returns hidden fields in the background

Front-end incoming format: password; name; age, ? Async find(CTX) {const {fields = ''} = ctx.query const selectFields = fields.split('; ').filter(f => f).map(f => '+' + f).join('') // we must await ctx.body = await user.find ().select(selectFields)}Copy the code
  • If the list is too large, we need to use paging lookupmongoodbprovideslimit skipfield
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 must not be less than or equal to 0 page = math.max (+page, 1) -1 Limit = math.max (+ math.max) Body = await user.find ().limit(limit).skip(page * limit).select(selectFields)}Copy the code
  • The list uses a fuzzy search, and a regular is done
Cosnt {q = "} = ctx.query await user.find ({name: new RegExp(q) // fuzzy search})Copy the code

What about multiple field searches?

await User.find({ $or: [{title: q}, {name: q}] })
Copy the code
  • Use reference associated tables

Do a focus on the user function, user module to add fields

Following: {type: [{type: schema.types.objectid, // use _id to associate ref: 'User' // reference to User table}]}Copy the code

Focus on controller

// follow async follow(CTX) { Const ownUser = await user.findByID (ctx.params.my_id) const ownUser = await user.findByid (ctx.params.my_id) // Mongoose uses toString () if (! ownUser.following.map(id => id.toString()).includes(ctx.params.id)) { ownUser.following.push(ctx.params.id) ownUser.save() } ctx.status = 204 }Copy the code

Use the PUT method to register routes

router.put('/following/:my_id/:id', follow)
Copy the code

Use postman to request a post-pull list

Use the populate keyword if you want to obtain details about your followers:

ctx.body = await User.find({ name: New RegExp(q) // Fuzzy search}).limit(limit).skip(page * limit).select(selectFields).populate('following')Copy the code

After want to write down the actual combat small example, small program or PC (VUe3) with Koa, but did not want to do what, interested friends can public number backstage message yo.

If this article is helpful to you, please share it in moments! Thanks for reading!