2022のMongoosejsシート

19604 ワード

マングースとは


MongGooseは、ORM(Object Document Manager)です.リレーショナルOMS(オブジェクトリレーションマネージャ)のように、より身近なプログラミングパターンのオブジェクトにデータベースのデータをマップします.マングースは特にJavaScriptアプリケーションのためのMongoDB ODMです、そして、この記事はMongooseを使用しているJSでMongoDBで働くための資源であることを目指します.
  • マングースを取り付けるnpm install mongoose
  • ロジックとフローはKOAまたはFastifyのような他のノードのWebフレームワークと同じであるべきですが、我々はExpressJSアプリケーションの文脈で多くの例を共有します.
  • マングースの里


    URIはユニバーサルリソース識別子、アプリケーションがメッセージを他のアプリケーションに送ることができる文字列を表します.私達は私達のお気に入りのウェブサイトにURLの形でHTTP URIをすべての時間を使用する.パターンは次の通りです.protocol://username:password@host:port/resource?query=string&key=value
  • protocol:// 送信されるメッセージの型https:// , mongodb:// , postgresql://
  • username:password@ ほとんどのWebページは一般的に使用されていないウェブサイトに公開されているので、1つはターゲットのために必要な場合、ユーザー名とパスワードは、通常、データベースに必要な場合.
  • host これは、宛先アプリケーションをホストするサーバのIPアドレスの別名であるドメインとサブドメインとなりますlocalhost 例えば、127.0.0.1 現在使用しているマシンです.
  • port あらゆるサーバは、65535(最高符号なし16ビット整数)まで番号をつけられた異なるポートの上でメッセージを受け取ることができます.ブラウザは知っているので、一般的にURL用のポートを入力しませんhttp ポート80と80へのトラフィックhttps ポート443へのトラフィックほとんどのデータベースにはデフォルトのポートがありますmongodb -> 27017 | postgresql -> 5432 | mysql -> 3306
  • /resource 受信先アプリケーションにどのリソースを送信先にアクセスするかを指定します.Webアプリケーションの場合は、通常、特定のWebページ、ファイル、またはJSONデータです.データベースアプリケーションの場合は、通常、アクセスされる特定のデータベースを参照します.
  • ?query=string&key=value これは、フォームまたはデータベース構成からデータのような追加情報を渡すために使用できるクエリ文字列です.
  • 私のPCで動くMongoサーバのためのMongoDB URIは、そうです:mongodb://username:[email protected]:27017/database_nameRead here for options that can be passed in the query string
    MongoDB URIは、アプリケーションでハードコーディングされることはありませんが、環境変数を介して、またはあなたの中に含まれているファイルを介して配送されます.ので、任意のリモートパブリック取得リポジトリでURLをエクスポートしない

    マングース輸入


    デフォルトでは、ライブラリをインポートするためにrequire .const mongoose = require("mongoose")あなたが加えるならば"type":"module" あなたのパッケージに.JSONプロジェクトはESモジュールのように扱われ、代わりに次のようになります.import mongoose from "mongoose"

    接続を確立する


    我々の目的のために、我々はmongo URIが呼ばれる変数に格納されると仮定しますDATABASE_URL この変数が存在することを確認し、URI文字列を保持します.The options 変数を指定すると、一覧表示できるデータベースの設定を持つJavaScriptオブジェクトを保持しますhere .
    //establish the connection
    mongoose.connect(DATABASE_URL, OPTIONS)
    
    // saving the connection in a variable
    const cxn = mongoose.connection
    
    //creating messages when connection changes state
    cxn
    .on("open", () => console.log("mongoose is connected"))
    .on("close", () => console.log("mongoose is disconnected"))
    .on("error", (error) => console.log(error))
    

    モデル


    モデルは私たちが保存し、我々のマングースデータベースから取得することができます.モデルを作成するには、まずデータベース内のデータの形(個々のプロパティとデータ型)を定義するスキーマを作成する必要があります.基本モデルの定義は以下のようにします.
    // destructure model function and Schema constructor from mongoose
    const {model, Schema} = mongoose
    
    // create a schema
    const UserSchema = new Schema({
    username: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    age: Number,
    email: String
    }, {timestamps: true})
    
    // create a model
    const User = model("User", UserSchema)
    
    details on the different schema data types and options
    details on working with models

    モデル法の使用


    モデルオブジェクトには、データベース内のデータを作成、削除、更新、検索する方法がたくさんあります.メソッドは3つの異なる方法で使用できます.我々は、これらの記述は、明示的なルートのコンテキストでは、任意のノードのWebフレームワークではかなり同じであるでしょう.
    Methods your models have
    // callback syntax
    app.get("/users", (req, res) => {
      // use the find method to find all users with the specified username
      User.find({username: req.query.username}, (error, results) => {
        // check if there is an error
        if(error){
          res.status(400).json({error})
          return false
        }
        // send results as json
        res.json(results)
      })
    })
    
    // .then syntax
    app.get("/users", (req, res) => {
      // use the find method and catch errors
      User.find({username: req.query.username})
      .then((results) => res.json(results))
      .catch((error) => res.status(400).json({error})
    })
    
    // async/await syntax
    app.get("/users", async (req, res) => {
      // use the find method, catch errors
      const results = await User.find({username: req.query.username}).catch((error) => res.status(400).json({error})
      // send results as response
      res.json(results)
    })
    

    取扱関連書類


    MongoDBはドキュメントのデータベースですので、関連するデータを処理するために最適ですが、mongooseは、多くの簡単に関連データを実装するためにいくつかのツールを構築します.

    最初のステップ:ObjectID型


    関係を表現するには、関連するフィールドをObjectID型の意味として指定します.これは、指定したコレクション内の関連ドキュメントのオブジェクトIDを表す文字列を保持するフィールドを想定します.
    // destructure model function and Schema constructor from mongoose
    const {model, Schema} = mongoose
    
    // create a schema
    const UserSchema = new Schema({
    username: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    age: Number,
    email: String,
    posts: [{type: mongoose.Types.ObjectId, ref: "Post"]
    }, {timestamps: true})
    
    const PostSchema = new Schema({
    title: String,
    body: String,
    author: {type: mongoose.types.ObjectId, ref: "User"}
    }, {timestamps: true})
    
    // create a model
    const User = model("User", UserSchema)
    const Post = model("Post", PostSchema)
    

    第2ステップ:互いに関連付けるレコード


    // grab two existing documents from both collection
    
    app.get("/createPost/:userId", async (req, res) => {
      const post = await Post.create(req.body) // create new post
      const user = await User.findById(req.params.userId) // get existing user
    
      // associate post with user
      post.author = user
      post.save()
    
      // associate user with post
      user.posts.push(post)
      user.save()
    
      // send back post as response with author populated
      res.json(await post.populate("author"))
    
    })
    
    The populate メソッドを使用すると、別のドキュメント(ObjectID型)に関連してマークされたフィールドを取得し、その関連ドキュメントからデータを入力することができます.この方法では、手動で別のクエリを実行する必要がなくなります.

    追加トピック

  • Validation
  • Model Middleware