当前位置:网站首页>Comparison of mongoose in express, KOA and egg

Comparison of mongoose in express, KOA and egg

2022-06-11 17:50:00 Liluyao

Mongoose What is it? ?

In a nutshell :Mongoose It's a set of operations MongoDB Database interface .

Start

In the use of mongoose Before , It needs to be installed in advance Node Environmental Science and MongoDB database .
The above is ready for us .

stay Express Koa Egg The use of

  • stay Express in
    First initialize the project

    npm init // Initialize project 
    npm i xxx --save// Install various dependencies such as express nodemon ...

    Directory as follows

    |-express
    |  | -- db// start-up mongodb Database dbpath route 
    |  | --model// The model of the table in the database 
    |  | --node_modules
    |  | --public// public resource 
    |  | --route// route 
    |  | --schema// Pattern type 
    |  | --app.js// Entrance file 
    |  | --package.json// The configuration file 

    install mongoose.

    npm install mongoose// install mongoose

    stay package.json

    {
    "dependencies": {
      "body-parser": "^1.19.0",
      "connect-multiparty": "^2.2.0",
      "express": "^4.17.1",
      "formidable": "^1.2.2",
      "http-proxy-middleware": "^2.0.0",
      "mongoose": "^5.12.13",
      "multer": "^1.4.2",
      "multiparty": "^4.2.2",
      "nodemon": "^2.0.7",
      "xlsx": "^0.17.4"
    }
    }
    

    stay app.js Introduce dependency in

    const express=require("express");// introduce express
    const mongoose = require('mongoose');// introduce mongoose
    const app=express();
    const port=8080;// Port number 
    mongoose.connect('mongodb://localhost:27017/Management',{useNewUrlParser:true,useUnifiedTopology:true},function(err){
      if(err){
          console.log(' link failure ');
      }else{
          console.log(' Link successful ');   
      }
    });// Linked database name Mangagement Port number 27017, Cancel database startup warning ,
    
    app.listen(port,()=>{
              console.log(`Example app listening at http://localhost:${port}`)
          })
    

    Open database
    In the installation mongodb/bin Directory execution cdm
    Execute the following instructions

    $ mongod  --dbpath=" Database path " --port= Port number 
    // for example 
    $ D:\Mongodb\bin> mongod  --dbpath="E:\myNode\Management\db" --port=27021

    And then again E:\myNode\Management perform

    nodemon app.js// If successful, the console will print 
     Link successful 
    Example app listening at http://localhost:8080
    // It indicates that the database link is successful 

    If the link is successful, we can MongoDB Database processing CURD operation
    stay schema The data table schema type is defined under the folder
    stay schema/user.js

    const mongoose=require('mongoose');
    module.exports=new mongoose.Schema({
      Mailbox:String,
      UserName:String,
      Password:String,
      Password01:String,
      Name:String,
      Phone:Number,
      ContactAddress:String,
      Passport:String,
      ID:Number,
      Company:String,
      TouristGuide:String,
      GoAbroad:String
    })

    stay model Folder definition data table model

    const mongoose=require('mongoose');
    const userSchema=require('../schema/user.js')
    module.exports=mongoose.model('User',userSchema)
    // Define the data table name as User however mongodb The name of the data table in is Users

    stay route Define the route under the folder

    const express=require('express');
    const multipart = require('connect-multiparty');//
    const XLSX=require("xlsx")// Read elsx file 
    const multipartMiddleware = multipart();
    
    const router=express.Router();
    const User=require('../model/user.js')
    let userData;
    router.use((req,res,next)=>{
      UserData={
          code:0,
          data:{},
          message:""
      }
      next();
    })
    // Upload excal surface 
    router.post('/uploadFile', multipartMiddleware, async function (req, res, next) {
      console.log(" success ")
      console.log(req.files.file.path)
     let excelData = [];   // For preservation 
     let reqData = [];
     const workbook = XLSX.readFile(req.files.file.path);// Read the file 
     console.log(workbook)
    
     const sheetNames = workbook.SheetNames;//[sheet1]
    for (var sheet in workbook.Sheets) {
        console.log(sheet)
      if (workbook.Sheets.hasOwnProperty(sheet)) {
        fromTo = workbook.Sheets[sheet]['!ref'];
        console.log(workbook.Sheets[sheet])
        console.log(fromTo)
        // analysis excel File get data 
        excelData = excelData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
      }
    }
    //excel Table date processing method 
    function excelDateFN(DataStr){
        var y = new Date(1900, 0, DataStr)
        var d=new Date(y)
        var m=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() 
        //+ ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(); 
        return m
    }
     console.log(excelData);
    for (var i = 0; i < excelData.length; i++) {
      reqData.push({
        id: excelData[i][' Number '],
        Name: excelData[i][' full name '],
        Sex: excelData[i][' Gender '],
        EName: excelData[i][' English name '],
        Nationality: excelData[i][' nationality '],
        BirthPlace: excelData[i][' Place of birth '],
        BirthDay: excelDateFN(excelData[i][' Date of birth ']),
        Passport: excelData[i][' passport No '],
        DateIssue: excelDateFN(excelData[i][' Passport date of issue ']),
        PeriodValidity: excelDateFN(excelData[i][' The passport is valid for ']),
        PlaceIssue: excelData[i][' Where the passport was issued '],     
        Visa: excelData[i][' Visa No '],
      })
    }
    // Data processing end call sql sentence , And return to the front desk 
     console.log(reqData);
     if(reqData.length!=0){
         UserData.code=1;
         UserData.message=" Upload successful ";
         UserData.data=reqData
         res.send(UserData)
     }else{
         UserData.code=1;
         UserData.message=" Upload failed ";
         UserData.data=""
         res.send(UserData)
     }
    //res.json(reqData)
    
     
    })
    
    // Information display 
    router.post("/personalData",(req,res)=>{
      const UserName=req.body.UserName
      
      User.findOne({UserName:UserName}).then((data)=>{
          if(data){
              UserData.code=1;
              UserData.message=" The request is successful ";
              UserData.data=data
              res.send(UserData)
          }
          
      })
      
    })
    // Modify the information 
    router.post("/revisePersonalData",(req,res)=>{
      console.log(req.body)
      const _id=req.body._id,
          UserName=req.body.UserName,
          Password=req.body.Password,
          Password01=req.body.Password01,
          Name=req.body.Name,
          Phone=req.body.Phone,
          ContactAddress=req.body.ContactAddress,
          Passport=req.body.Passport,
          ID=req.body.ID,
          Company=req.body.Company
      const updateFields = {
                      _id,
                      UserName,
                      Password,
                      Password01,
                      Name,
                      Phone,
                      ContactAddress,
                      Passport,
                      ID,
                      Company
                              };
      User.findByIdAndUpdate({_id:_id},updateFields,(err,data)=>{
          if(data){
              UserData.code=1;
              UserData.message=" Modification successful ";
              
              res.send(UserData)
          }
      })
      
        
    })
    // register 
    router.post('/logon',(req,res)=>{
          const UserName=req.body.UserName
          const Password=req.body.Password
          const Password01=req.body.Password01
          const Name=req.body.Name
          const Phone=req.body.Phone
          const ContactAddress=req.body.ContactAddress
          const Passport=req.body.Passport
          const ID=req.body.ID
          const Company=req.body.Company
      //console.log(req.body)
      User.findOne({UserName:UserName}).then(function(data){
          console.log(data)
          if(data){
              UserData.code=3;
              UserData.message=" User name already exists ";
              res.send(UserData)
          }else{
              let newUser=new User({
                  UserName:UserName,
                  Password:Password,
                  Password01:Password01,
                  Name:Name,
                  Phone:Phone,
                  ContactAddress:ContactAddress,
                  Passport:Passport,
                  ID:ID,
                  Company:Company,    
              })
               newUser.save()
               UserData.code=1;
               UserData.message=" Registered successfully ";
               res.send(UserData)
          }
      })
      
    })
    // Sign in 
    router.post('/register',(req,res)=>{
      let userName=req.body.userName;
      let password=req.body.passWord;
       console.log(req.body)
      User.find({UserName:userName,Password:password}).then((data)=>{
          console.log(data)
          if(data){
              console.log(' Login successful ')
              UserData.code=1
              UserData.message=" Login successful "
              res.send(UserData)
          }else{
              console.log(' Login successful ')
              UserData.code=2
              UserData.message=" The username does not exist "
              res.send(UserData)
          }
      })
      
    })
    module.exports=router

    stay app.js Use routing in

    app.use('/User',require('./route/user.js'))

    Interface :
    register :http://localhost:8080/User/login
    Sign in :http://localhost:8080/User/re...
    Upload :http://localhost:8080/User/up...
    lookup :http://localhost:8080/User/pe...
    modify :http://localhost:8080/User/re...

  • stay Koa in
    First initialize the project

    npm init // Initialize project 
    npm i xxx --save// Install various dependencies such as koa nodemon ...

    Directory as follows

    |-koa
    |  | -- db// start-up mongodb Database dbpath route 
    |  | --model// The model of the table in the database 
    |  | --node_modules
    |  | --public// public resource 
    |  | --route// route 
    |  | --schema// Pattern type 
    |  | --app.js// Entrance file 
    |  | --package.json// The configuration file 

    install mongoose.

    npm install mongoose// install mongoose

    stay package.json

    {
    "name": "vietnam",
    "version": "1.0.0",
    "description": " Vietnam visa management system interface project ",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node app.js"
    },
    "author": " Liluyao ",
    "license": "ISC",
    "dependencies": {
      "@koa/multer": "^3.0.0",
      "koa": "^2.13.1",
      "koa-body": "^4.2.0",
      "koa-bodyparser": "^4.3.0",
      "koa-router": "^10.0.0",
      "koa-static": "^5.0.0",
      "koa2-cors": "^2.0.6",
      "mongodb": "^4.0.1",
      "mongoose": "^5.13.5",
      "multer": "^1.4.2",
      "path": "^0.12.7"
    },
    "devDependencies": {}
    }
    
    

    stay app.js Introduce dependency in

    const Koa=require('koa');
    const cors = require('koa2-cors');// Cross domain packages 
    const mongoose=require('mongoose');
    const router=require('koa-router')()// route 
    const koaStatic=require('koa-static')// static state 
    const koaBody=require('koa-body');//
    const multer = require('@koa/multer');
    const bodyParser=require('koa-bodyparser')//post request 
    const path=require('path');
    const app=new Koa();
    
    
    var storage = multer.diskStorage({
      // File save path 
      destination: function(req, file, cb) {
          cb(null,path.join(__dirname ,'/public/uploads'))
      },
      // Modify file name 
      filename: function(req, file, cb) {
          let type = file.originalname.split('.')[1]
          cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
      }
    })
    // Load the configuration 
    //
    
    var upload = multer({storage});
    router.post('/upload',upload.single('File'), async(ctx, next) => {
      console.log(ctx.request)
    ctx.body = `${ctx.origin}/public/uploads/${ctx.file.filename}`
    })
    
    let register=require('./routes/register.js')
    let vise=require('./routes/visa.js')
    let DataList=require('./routes/datalist.js')
    router.use(register.routes())// Login interface 
    router.use(vise.routes())// Visa interface 
    router.use(DataList.routes())
    app.use(cors())// Allow cross-domain 
    
    app.use(bodyParser())// Enable bodyParser solve post request 
    app.use(router.routes())// Enable routing 
    app.use(router.allowedMethods()) 
    mongoose.connect('mongodb://localhost:27018/VietNam',{useNewUrlParser:true,useUnifiedTopology:true},(err)=>{
      if(err){
          console.log(' link failure ');
      }else{
          console.log(' Link successful ');    
          {
              // Create new table 
              //const dataList=mongoose.model(' Data table name ',{" Healthy name ": type })
              //const kitty = new dataList({" Key name ":" Key value "})
              //kitty.save().then(() => console.log(' I am creating a new data table '));
          }
          
      };
      })// Data table name VietNam Port number 27018 Cancel database startup warning 
    app.listen(3001,()=>{
      console.log('http://localhost:3001')
    });

    Open database
    In the installation mongodb/bin Directory execution cdm
    Execute the following instructions

    $ mongod  --dbpath=" Database path " --port= Port number 
    // for example 
    $ D:\Mongodb\bin> mongod  --dbpath="E:\myNode\VietNam\db" --port=27018

    And then again E:\myNode\Management perform

    nodemon app.js// If successful, the console will print 
     Link successful 
    http://localhost:3001
    // It indicates that the database link is successful 

    If the link is successful, we can MongoDB Database processing CURD operation
    stay schema The data table schema type is defined under the folder
    stay schema/user.js

    // and express Use the same way 
    const mongoose=require('mongoose');
    module.exports=new mongoose.Schema({
      UserName:String,
      Password:String,
    })

    stay model Folder definition data table model

    // and express Use the same way 
    const mongoose=require('mongoose');
    const userSchema=require('../schema/user.js')
    module.exports=mongoose.model('User',userSchema)
    // Define the data table name as User however mongodb The name of the data table in is Users

    stay route Define the route under the folder

    const Router=require('koa-router');
    const router=new Router();
    const Visa=require('../model/visa.js');
    router.post('/visa',async (ctx,next)=>{
      console.log(ctx.request.body.ID)
      ctx.response.status=200
      let VisaU= await Visa.find({"ID":ctx.request.body.ID})
      const obj={
          detail:[]
      }
      let User=VisaU[0]    
      console.log(User)
      if(User===undefined){
          //obj.msg=" The order does not exist "
          ctx.body=obj
      }else{
          //obj.msg=" The query is successful "
          obj.detail=User
          ctx.body=obj
          
      }
      //ctx.body=User
    })
    module.exports=router

    stay app.js Use routing in

    let vise=require('./routes/visa.js')
    router.use(vise.routes())// Visa interface 

    Interface :
    visa :http://localhost:8080/visa

  • stay Egg in
    First initialize the project

    $ mkdir project-name// Create an empty folder 
    $ npm init egg --type=simple//simple Indicates the skeleton type 

    Directory as follows :

    |-app// Main development documents 
    |   |-- controller// Parsing user input , Return corresponding results after processing 
    |   |-- db// start-up mongodb Database dbpath route ( Optional )
    |   |--extend// Extensions to the framework ( Built in object extensions )
    |   |    |---application.js//( Fixed name )
    |   |    |---context.js//( Fixed name )
    |   |    |---request.js//( Fixed name )
    |   |    |---response.js//( Fixed name )
    |   |    |---helper.js//( Fixed name )
    |   |--middleware// Authoring middleware 
    |   |--model// The model of the table in the database 
    |   |--publie// Static resources 
    |   |--schedule// Timing task 
    |   |--service// Write the business logic layer 
    |   |--view// Template file 
    |   |---router.js// To configure  URL  route 
    |-config// Store the configuration file 
    |   |--config.default.js// For writing configuration files 
    |   |--plugin.js// Configure the plug-ins to be loaded 
    |-test// Storage unit test 
    |-logs// Log files 
    |-package.json// Project description 

    download egg-mongoose

    npm i egg-mongoose --save

    To configure config/plugin.js

    'use strict';
    module.exports = {
    mongoose:{
       enable:true,
       package:"egg-mongoose" 
    }
    };

    stay config/config.default.js

    'use strict';
    module.exports = appInfo => {
    const config = exports = {};
    // use for cookie sign key, should change to your own and keep security
    config.keys = appInfo.name + '_1641975352438_173';
    // add your middleware config here
    config.middleware = [];
    // add your user config here
    const userConfig = {
      // myAppName: 'egg',
    };
     
     //mongoose Database configuration 
    config.mongoose={
        url:'mongodb://127.0.0.1:27021/VietNamVisa',// Port number 27021 Database name VietNamVisa
        options:{useNewUrlParser:true,useUnifiedTopology:true},// Other configuration warning removal methods 
    }
    
    return {
      ...config,
      ...userConfig,
    };
    };

    Open database

Turn on the mongodb Under folder bin Catalog cmd
perform mongod --dbpath= Path to store data --port= The port number of the database
for example

mongod  --dbpath=E:\myNode\VietNamVisa\init\app\db    --port=27021

And then again E:\myNode\VietNamVisa perform

 npm run dev// Start project 

stay app/model/visaOnArrivalModel.js
Create a model

module.exports=app=>{
    const {mongoose}=app;
    const {Schema}=mongoose;
    const VisaOnArrivalSchema=new Schema({
        // The order number 
        OrderNumber:{type:String},
        // full name 
        FullName:{type:String},
        // passport No 
        PassportNo:{type:String},
        // Departure flight number 
        DepartureFlightNumber:{type:String},
        // Time of entry 
        TimeOfEntry:{type:String},
        // Arrive at the airport 
        ArriveAtTheAirport:{type:String},
        // flight number 
        FlightNumber:{type:String},
        // English name 
        EnglishName:{type:String},
        // Gender 
        Gender:{type:String},
        // Date of birth 
        DateOfBirth:{type:String},
        // nationality 
        Nationality:{type:String},
        // Passport date of issue 
        PassportIssueDate:{type:String},
        // The passport is valid for 
        PassportPeriodOfValidity:{type:String},
        // Departure date 
        DepartureDate:{type:String},
        // Departure city 
        DepartureCity:{type:String},
        // Type of approval 
        Type:{type:String},
        // Status of approval document 
        Status:{type:String},
        //Checked:{type:Boolean}
    });
    return mongoose.model("VisaOnArrivalModel",VisaOnArrivalSchema,"visaonarrivals")
    }
// A sheet named visaonarrivals Data sheet for 

stay app/service/visaOnArrivalService.js
Write the business logic for operating the database

"use strict"
const Service=require("egg").Service;
class VisaOnArrivalService extends Service {
    async VisaOnArrival(obj){
        const {ctx}=this;
        
            // Store the data 
            // Be careful !!!!ctx.model.xxx in xxx refer to model The file name of is capitalized 
         const VisaOnArrivalList = new ctx.model.VisaOnArrivalModel({
                        OrderNumber:obj.OrderNumber,
                         // full name 
                        FullName:obj.FullName,
                        // passport No 
                        PassportNo:obj.PassportNo,
                        // Departure flight number 
                        DepartureFlightNumber:obj.DepartureFlightNumber,
                        // Time of entry 
                         TimeOfEntry:obj.TimeOfEntry,
                        // Arrive at the airport 
                        ArriveAtTheAirport:obj.ArriveAtTheAirport,
                        // flight number 
                        FlightNumber:obj.,
                        // English name 
                         EnglishName:obj.FlightNumber,
                         // Gender 
                         Gender:obj.Gender,
                        // Date of birth 
                        DateOfBirth:obj.DateOfBirth,
                         // nationality 
                         Nationality:obj.Nationality,
                        // Passport date of issue 
                         PassportIssueDate:obj.PassportIssueDate,
                         // The passport is valid for 
                        PassportPeriodOfValidity:obj.PassportPeriodOfValidity,
                         // Departure date 
                         DepartureDate:obj.DepartureDate,
                       // Departure city 
                         DepartureCity:obj.DepartureCity,
                         // type 
                         Type:obj.Type,
                         // Status of approval document 
                        Status:obj.Status,              
                     });
                   //  Data saved to database 
                    VisaOnArrivalList.save();
                    return " Add success "
                    }
    
}
module.exports=VisaOnArrivalService;

stay app/controller/visaOnArrival.js
Write about parsing user input , Return corresponding results after processing

"use strict"
const Controller=require('egg').Controller;
class VisaOnArrival extends Controller {
    async VisaOnArrival(){
        const {ctx}=this
        //const req=ctx.request.body
        const res=await ctx.service.visaOnArrivalService.VisaOnArrival(req)
        //console.log(res)
        ctx.body={
            state:200,
            msg:res
        }
    }
}
module.exports=VisaOnArrival

stay app/router.js
Write routing

'use strict';
module.exports = app => {
  const { router, controller } = app;
 // Add data 
  router.post("/AddVisaOnArrival",controller.visaOnArrival.VisaOnArrival);
};

summary

That's about Mongoose stay Express、Koa、 Egg Use contrast in ,Mongoose stay Express、Koa There is no difference in the use of . stay Egg Compared with the other two frameworks, there are major changes in the use of . The biggest difference is based on the characteristics of the framework itself . The first two frameworks don't have many conventions , The writing is free and easy , It is written completely according to the developer's own preferences .Egg The feature convention is better than the configuration . Developer writing is more standardized and unified .

原网站

版权声明
本文为[Liluyao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011853081861.html