Practical Training Json - importing background data and modularization

Posted by danmahoney245 on Wed, 01 Dec 2021 06:49:30 +0100

The content of this article is:

Terminal: nodemon app.js start application

  1. npm install mongoose – sane install Mongoose
  2. nodemon app.js launch the application

Content added in app.js code page:

The import function is equivalent to accessing here after export. This is the path directly referenced

Example:

const tagRouter = require("./routers/tag.router");

const userRouter = require("./routers/user.router");

const contentRouter = require("./routers/content.router");

The following is the usage function, which is the tag.router.js (TAB), user.router.js (user page) and content.router.js (content page) created in the back

Example:

//Use function

// const router = new Router();

tagRouter(router); // Because it is a function, you can write parameters directly

userRouter(router); // This is the function of the user's router

contentRouter(router); // This is the router function of the content

How to write the exported function:

Example:

//User routing modularization

//Export function

module.exports = function (router) {

    // The async ctx processing function processes the contents of {}

    router.get("/user", async ctx => {

        ctx.body = "user";

    })

}

Today's main contents are: the addition (although it can be run, it is not perfect) and deletion (the deletion step has not yet started). It is necessary to remember the error prone areas:

1, The correct way to write mongodb is: mongodb, one o in the middle, not two

2, Link: establish database links, add, delete, modify and query specific operations   In addition, mongodb recognizes the case. Note that the case in the link address cannot be confused.

 

The general steps of Mongodb.js page are as follows: 1. First import is also a reference. 2. First create a model and constrain the data. 3. Generate (generate specific content steps)    It can also be the name of the collection

 

There is no table on Mongodb  : NoSQL(NoSQL = Not Only SQL), which means "not just SQL"

What is Mongodb?

MongoDB is written in C + + language. It is an open source database system based on distributed file storage.

In the case of high load, adding more nodes can ensure the server performance.

MongoDB aims to provide scalable high-performance data storage solutions for WEB applications.

MongoDB stores data as a document, and the data structure consists of key value (key = > value) pairs. A MongoDB document is similar to a JSON object. Field values can contain other documents, arrays, and document arrays.

 

 

 

 

 

 

 

SQL terms / concepts

MongoDB terms / concepts

Explanation / explanation

database

database

database

table

collection

Database tables / sets

row

document

Data record line / document

column

field

Data field / field

index

index

Indexes

table joins

 

Table connection, not supported by MongoDB

primary key

primary key

Primary key, MongoDB will automatically_ The id field is set as the primary key

Through the example below, we can also more intuitively understand some concepts in Mongo:

 

database

Multiple databases can be established in one mongodb.

The default database of MongoDB is "db", which is stored in the data directory.

A single instance of MongoDB can accommodate multiple independent databases, each with its own set and permissions, and different databases are placed in different files.

 

Find is the query condition

Schema  : constraint

 

app.js content:

 
// ctrl+c  End operation

//The object system is imported directly
const Koa = require('koa');
// The first letter of the definition in this place shall be capitalized, and shall be consistent with the following route creation
const Router = require('koa-router'); //introduce koa-router Routing Middleware
const koaBody = require('koa-body'); //The native is used to parse the data. The operation is slightly complex, and the koa-body,But simplify the code and focus on business logic
// The import function is equivalent to accessing the path directly referenced here after export
const tagRouter = require("./routers/tag.router");
const userRouter = require("./routers/user.router");
const contentRouter = require("./routers/content.router");

// Introducing internal methods or properties
// const {Method or property name} = require('koa');

// create object
const app = new Koa();
// use
app.use(koaBody());
const router = new Router();//Create routes and support parameter transfer==instantiation 

// Use function
// const router = new Router();
tagRouter(router); // Because it is a function, you can write parameters directly
userRouter(router); // This is the user's router Function of
contentRouter(router); //This is the content router Function of

// response middleware ==>use()namely use(use)Middleware is use()Content of 
// app.use(async (ctx,next) => {
// //   ctx.body = 'Hello World';
//     ctx.body = 'Hello Koa2';
//     next(); //This directly allows it to find the next address after the middleware is completed
// });

// koa Support asynchronous functions async--Formal parameter
// "/" The requested route (root directory)
// router.get("/", async (ctx)=>{
//    //query Looking for url Parameters<==>url parameter ctx.query
//   console.log(ctx.url); //Routing address with parameters
//   console.log(ctx.query); // Acquired json object
//   // This is a string
//   // console.log(ctx.querystring); //String passed
// });

// // postman 
// // This is post How to write the request"/a"Is to be different from the path of the root directory/a What's inside
// router.post("/a",async ctx =>{
//   console.log(ctx.url);
//   // console.log(query);
//   console.log(ctx.request.body);
//   // Send request to server
//   ctx.body = "Request succeeded"
// });

// Create a route before starting the service
// call router.routes()To assemble the matched route and return a merged middleware
// call router.allowedMethods()Get a middleware. When a non-conforming request is sent, it will return `405 Method Not Allowed` or `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({ 
    // throw: true, // Throw an error instead of setting the response header status
    // notImplemented: () => 'The functionality required by the current request is not supported',
    // methodNotAllowed: () => 'Unsupported request mode'
}));
// app.use(router.routes()).use(router.allowedMethods()); //You can write two in this way, which is the simplest
// localhost:3000 // listen Listening is the content in the port (also the open port address)
app.listen(3000,()=>{
  console.log("http://localhost:3000");
});

mongodb.js Content:

// 1.Import reference first
const mongoose = require("mongoose");
const userRouter = require("./routers/user.router");
// Link establish database links for addition, deletion, modification and query  mongodb:Recognize case and pay attention to case
mongoose.connect("mongodb://127.0.0.1:27017/text");
// 2.First create a model to constrain the data
const tagSchema = new mongoose.Schema({ // Schema If you don't have a model, you can add anything to it{}Inside is a constraint
    // text:String, // String Type text
    text: {
        type: String,
        minlength: 2,
        maxlength: 12
    }

});

// 3. generate
// Set name  
const tagModel = new mongoose.model("tag", tagSchema);
// tagModel

// export tagModel After exporting, you can tagModel Write, add, delete, modify and check, the above tagSchema It can't be used outside this page
module.exports = tagModel;
// module.exports = userRouter;

// const arr=[{text:"HTML"},{text:"QSL"},{text:"NodeJs"}]
// // tagModel.insertMany Collections can be inserted into collections
// // arr :   , function(error Return error message,docs  content)Are callback functions 
// tagModel.insertMany(arr,function(error,docs){
//     console.log(error);
//     console.log(docs);
// })