Node.js操作データベース(MySQL/Mongoose)エッセイ

11999 ワード

リレーショナル・データベースと非リレーショナル・データベース
  • リレーショナル・データベース(MySQLなど)
  • すべてのリレーショナル・データベースは、sql言語で
  • 操作されます.
  • すべてのリレーショナル・データベースは、操作前にテーブル構造
  • を設計する必要があります.
  • テーブル構造サポート制約:一意、プライマリ・キー、デフォルト値、空でない
  • 非リレーショナル・データベース(MongDBなど)
  • 非関係型データベース類似key-valueのキー値対
  • MongoDB最も似た関係型データベースの非関係型データベース
  • データベース=』データベース
  • データテーブル=』コレクション(配列)
  • テーブルレコード=』ドキュメント(オブジェクト)


  • MySQL
  • mysql
  • をインストール
    純粋な英語のパスに解凍
    MySQL     
    C:/Develop/mysql
            
    /Develop/mysql/data
    

    ディレクトリを解凍してmyを追加します.ini(プロファイル)は、次のようになります.
    [mysqld]
    #       ,            
    character-set-server=utf8
    

    管理者としてCMDを実行するには、次のコマンドを実行し、MySQLサービスをインストールします.
    //          bin    
    cd /bin
    //                      
    mysqld --initialize --user=mysql --console
    //  MySQL               
    mysqld --install MySQL
    

    MySQLサーバーにログインし、パスワードをリセット
    //           MySQL     
    mysql -u root -p
    Enter password: #       
    //         ,      
    mysql> set password for root@localhost = password('123');
    
  • データベース
  • の起動と停止
    ローカルサービスでmysqlを起動または閉じる
  • データベース(mysql.exeコマンドラインクライアントツール)
  • にアクセス
    cd /bin
    mysql -u root -p
    Enter password: #           
    

    -データベース管理ツール
    データベース管理ツールは本質的にデータベースサーバソフトウェア(Server)が提供するサービスを使用するデータベースクライアント(Client)コマンドラインツール、ビジュアル化ツールである.
  • 基本コマンド操作(単純操作データベース)
  •     mysql> show databases;  --        
        mysql> create database ;  --             
        mysql> use ;  --        ,           
        mysql> show tables;  --             
        mysql> create table  (id int, name varchar(20), age int);  --             ,    3   
        mysql> desc ;  --        
        mysql> source ./path/to/sql-file.sql  --      SQL      SQL   
        mysql> drop table ;  --             
        mysql> drop database ;  --             
        mysql> exit|quit;  --        
    
  • ビジュアル化ツールNavicat Premium(複雑な操作データベース)
  • Node.jsでの操作Mysqlデータベース
    サードパーティ製パッケージmysqlを使用してデータベースを操作する
  • mysqlの基本概念
  • データベース(データベースサービスソフトウェア/データの倉庫)
  • フィールド-カラム
  • を指します.
  • フィールドタイプ-カラムに格納可能なデータの種類を指します
  • int
  • char(length)
  • varchar(length)
  • date
  • decimal


  • 取付npm install mysql
  • hello word
  • var mysql = require('mysql');
    
    // 1.     
    var connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '199547com',
      database: 'demo' 
    
    // 2.       
    connection.connect();
    
    // 3.        
    connection.query('SELECT * FROM `songs`', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results);
    });
    
    // 4.     
    connection.end();
    
  • crud増加
  • //      
    insert into users values (null, '  ', 0, '2020-12-12', '12312');
    //    
    insert into users (name, gender, avatar) values ('  ', 0, '12312');
    

    検索
    //       
    select * from users;
    //    (select   [,   2] from   )
    select id, name, birthday from users;
    select `id`, `title`, `name` from `users`;
    

    変更
    --     
    update users set name = '  ', gender = 0
    

    削除
    delete from users where id = 6
    delete from users where id = 6 and gender = 0
    delete from users where id = 6 or gender = 0
    delete from users where id > 6
    delete from users where id in (4, 5)
    

    MongoDB
  • mongodbをインストールし、cmd入力mongod --version
  • に成功したかどうかを検証します.
  • データベース(mongod.exeデータベースサービスプログラム)
  • の起動と停止
    //  
    //mongodb    mongod  ,         /data/db           。
    //         ,       /data/db
    mongod
    
    //  
             ,  ctrl+c        
    
  • データベース(mongo.exeコマンドラインクライアントツール)
  • へのアクセスと終了
    //  
    mongo
    //  
    exit
    
  • 基本コマンド操作
  • show dbs               //          
    db                     //          
    show collections       //            
    use               //         ,       
    db.    .insertOne({"name":"jack"})  //    
    db.    .find()    //            
    

    Node.jsでの操作MongoDBデータベース
    サードパーティ製パッケージmongose(node.js公式パッケージmongodbに基づいて再パッケージ)を使用してmongodbデータベースを操作する
  • moogodbの基本概念
  • は、複数のデータベース
  • を有することができる.
  • 1 1つのデータベースに複数の集合collections(テーブル)
  • があり得る
  • 1の集合collectionsに複数のドキュメントdocument
  • がある.
    {
    // taobao、jidao、qq         ,   db          
    // users、products       collections              s    
    //    collections              document,     Schema    。
      qq: {
        user: [
          { name: "  " age: 18},
          { name: "  " age: 18},
          { name: "  " age: 18},
          { name: "  " age: 18},
          { name: "  " age: 18},
          ...
        ],
        product: [
    
        ],
        ...
      },
      taobao: {
    
      },
      jidao: {
    
      },
      baidu: {
    
      },
      ...
    }
    
  • 取付npm install mongoose
  • hello word
  • var mongoose = require('mongoose')
    mongoose.connect('mongodHb://localhost:27017/test', { useNewUrlParser: true })
    
    var Cat = mongoose.model('Cat', { name: String })
    
    var kitty = new Cat({ name: 'Zildjian' })
    kitty.save().then(() => console.log('meow'))
    
  • crud

  • Mongooseでは、すべてのデータが1つのSchemaによって作成されます.各schemaはMongodbの集合(collection)にマッピングされ、その集合(collection)内のドキュメント(document)の形式が定義されます.
    var mongoose = require('mongoose')            //  mongoose  
    mongoose.connect('mongodb://localhost/itcast')//   mongoDB     ,         
    
    var Schema = mongoose.Schema                  //   mongoose        
    var userSchema = new Schema({                 //       (   )
      username: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      },
      email: {
        type: String
      }
    })
    //        collections   Users
    //           /  /docuemnt         Schema       
    //           
    var  User = mongoose.model('User', userSchema) 
    //           
    module.exports = mongoose.model('User', userSchema)
    

    機能の追加
    var admin = new User({
      username: 'zs',
      password: '123',
      email: '[email protected]'
    })
    
    admin.save(function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log('    ')
      }
    })
    

    クエリー機能
    //      
    User.find(function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log('    ')
        console.log(ret)
      }
    })
    //        
    User.find({
      _id: '5ca3894ee78a732a245e3bb8',
      username: 'zs'
    }, function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log(ret)
      }
    })
    //            
    User.findOne({
      username: 'zs'
    }, function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log(ret)
      }
    })
    //  id     
    User.findById('5ca3894ee78a732a245e3bb8', function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log(ret)
      }
    })
    

    更新機能
    User.findByIdAndUpdate('5ca3894ee78a732a245e3bb8', {
      username: 'll',
      password: '8888'
    }, function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log('    ')
        console.log(ret)
      }
    })
    

    削除機能
    User.findByIdAndDelete('5ca3894ee78a732a245e3bb8', function (err, ret) {
      if (err) {
        console.log('    ')
      } else {
        console.log('    ')
        console.log(ret)
      }
    })
    

    転載先:https://juejin.im/post/5ca35516e51d453f5258e8e2