Node JS 및 MongodB Atlas를 사용하여 CRUD 애플리케이션 구축

안녕하세요!!
본고에서 우리는 MongoDBusingNode JSlibrary에서 Mogoose 데이터베이스를 어떻게 사용하는지 배울 것이다. 이것은 업계에서 광범위하게 사용되는 매우 유행하는 라이브러리이다.

In this article we had used the MongoDB Cloud service called MongoDB Atlas, you can also use the MongoDB server running locally, the process remains the same.


족제비는 무엇입니까?


Mongoose는 MongoDB와 Node에 사용되는 Object Data Modeling (ODM) 라이브러리입니다.js.이는 데이터 간의 관계를 관리하고 패턴 검증을 제공하며 objects in code와 이 데이터의 표시objects in MongoDB 사이를 전환하는 데 사용된다.

MongoDb VS SQL

MongoDB는 모드가 없는 NosQL 문서 데이터베이스입니다.이것은 SQL 데이터베이스처럼 강제적으로 실행되지 않기 때문에 문서JSON를 저장할 수 있다는 것을 의미한다.이것은 NoSQL을 사용하는 장점 중 하나입니다. 왜냐하면 응용 프로그램 개발을 가속화하고 배치의 복잡성을 낮추기 때문입니다.
다음은 데이터가 MongoSQL 데이터베이스에 저장되는 방법의 예입니다.


Mongoose는 아주 좋은documentation, 문서here를 보면 Mongoose에 대한 정보를 더 많이 알 수 있습니다.

족제비


수장하다


Mongo의 'Collections'는 관계 데이터베이스에 있는 표와 같다.여러 JSON 문서를 저장할 수 있습니다.

서류

'Documents'는 SQL의 레코드나 데이터 행과 같습니다.SQL 줄은 다른 테이블의 데이터를 인용할 수 있지만, Mongo 문서는 보통 이 데이터를 한 문서에 통합합니다.

영역

'Fields' 또는 속성은 SQL 테이블의 열과 유사합니다.

패턴


Mongo에는 모드가 없지만 SQL은 테이블을 통해 모드를 정의합니다.Mongoose'schema'는 응용층을 통해 강제로 실행되는 문서 데이터 구조(또는 문서 모양)이다.

모델

'Models'는 고급 구조 함수로 모델을 사용하고 관계 데이터베이스에 기록된 것과 같은 효과를 가진 문서 실례를 만든다.

​족제비가 움직인다


인용하다


이제 족제비Schema와 족제비Model의 미세한 차이를 볼 수 있고, 그 다음에 족제비와 합작을 시작하여 각 개념을 한 걸음 한 걸음 설명할 것이다.

족제비 모드와 모형


족제비model는 족제비schema의 포장물이다.Mongoose 모델은 문서의 구조, 기본값, 검증기 등을 정의했고 Mongoose 모델은 데이터베이스에 인터페이스를 제공하여 기록을 창설, 조회, 갱신, 삭제하는 데 사용했다.
지금 급하게 인코딩하지 말고 먼저 patience를 눌러라. 이제 이 장들을 읽기만 하면 된다. 다음 장절에서 우리는 한 걸음 한 걸음 프로젝트를 만들고 설정할 것이다.)
족제비 모형은 주로 three 부분을 포함한다.
  • 참조 족제비
  • 정의 모드
  • 모델 내보내기
  • 1. 족제비 참조


    const mongoose = require('mongoose')
    
    이것reference은 우리가 데이터베이스에 연결할 때 되돌아오는 것과 같다. 이것은 모델과 모델 정의가 데이터베이스에 현시적으로 연결될 필요가 없다는 것을 의미한다. 우리는 다음 절에서 볼 것이다database connection.
    이제 mongoose에서 reference to Schema 클래스를 만듭니다.
    const Schema = mongoose.Schema;
    
    이제 우리 자신을 계속 만들자Schema.

    2. 정의 모드


    const todoSchema = new Schema(
      {
        description: {
          type: String,
          required: true,
        },
      },
    );
    
    
    따라서 Schema 인스턴스를 만들고 이름todoSchema을 지정합니다.모드는 대상을 매개 변수로 하기 때문에 우리는 대상을 전달했다. 그중에 description라는 키가 있고 그 값도 하나의 대상이다. 우리는 그 중에서'String'형식의 필드 설명이 필요하다고 지정했다.이런 유형은 몬고우스에 내장되어 있습니다. 정부측 docs 에서 더 많은 정보를 볼 수 있고, 또한 필수 필드이기 때문에 키 requiredboolean 값true로 정의했습니다.
    모드에 더 많은 필드를 추가하고,
    const todoSchema = new Schema(
      {
        description: {
          type: String,
          required: true,
        },
        completed: {
          type: Boolean,
          default: false,
        },
      },
      {
        timestamps: true,
      }
    );
    
    
    마찬가지로, Boolean 형식이고 기본값false가 있는 completed 필드를 정의했습니다.
    구조를 자세히 살펴보면 두 번째 파라미터가 전달됩니다. 이것은 키가 있는 대상timestamps이기 때문에 두 번째 파라미터는 설정 대상입니다. 우리는 몬고우스의 내장 기능만 사용했고 문서마다 추가 필드, 즉 createdAtupdatedAt를 추가했습니다.
    다음을 허용합니다Schema Types.
  • 어레이
  • 부울 값
  • 버퍼
  • 날짜
  • 혼합(공통/유연한 데이터 유형)
  • 번호
  • 객체 ID
  • 문자열
  • 3. 모델 내보내기


    마지막으로 데이터베이스와 상호작용이 필요한 다른 모듈에서 사용할 수 있도록 우리가 만든 Schema 모델을 사용하고 내보냅니다.
    ​Mongoose 실례에서 model constructor를 호출하고 집합의 이름과 reference를 모델 정의에 전달해야 합니다.
    var Todos = mongoose.model("Todo", todoSchema);
    
    이제 마지막으로 이 모델을 내보냅니다. 그러면 전체 프로젝트에서 이 모델을 사용할 수 있습니다.
    module.exports = Todos;
    
    현재, 우리는 어떻게 정의하는지 schema, 그리고 어떻게 모드를 사용해서 만드는지 model 를 이해했다.그래서 이것은 족제비 모형이 만들어진 주요 부분인데, 지금 우리는 이 모형을 이용해야 한다.
    다음에 우리는 어떻게 setup the project 하는지 보고 code 작성을 시작할 것이다.

    응용 프로그램 만들기


    ​프로젝트 폴더node-mongoose를 만들고, 프로젝트 폴더에 models라는 폴더를 만들고, 폴더에 todos.js라는 파일을 만들고, 다음 코드를 붙여넣습니다. 모델 파일은 다음과 같습니다.
    // models/todos.js
    
    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    
    const todoSchema = new Schema(
      {
        description: {
          type: String,
          required: [true, "please enter task details"],
        },
        completed: {
          type: Boolean,
          default: false,
        },
      },
      {
        timestamps: true,
      }
    );
    
    var Todos = mongoose.model("Todo", todoSchema);
    
    module.exports = Todos;
    
    이전에 우리는 이 모델을 실현했습니다. 이 검사를 따르지 않았다면, 이 부분을 계속할 수 있습니다.

    폴더 구조:


    node-mongoose
      - models
         - todos.js
    
    이제 터미널, 즉 프로젝트의 루트 폴더todos.js를 열고 다음 단계를 수행합니다. -
  • Referencing Mongoose Section above
  • 라는 파일을 만듭니다.
  • 사용node-mongooseexpress 설치
  • 사용npm init -y족제비 설치
  • 사용app.jsdotenv 설치
  • 프로젝트
  • 의 루트 폴더에 npm install express라는 파일을 만듭니다.
  • 현재 이 블로그의 절차에 따라 npm install mongoose는 다음과 같다.npm install dotenv
  • 루트 폴더
  • 에 생성app.js 파일
  • 에 이 행을 추가합니다.암호와 데이터베이스 이름이 있는 env 파일database url
  • Github 등 서비스에 코드를 저장할 때 다른 사람이 데이터베이스 연결을 보지 않도록 확보할 수 있습니다.mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority 파일을 만들고 파일 이름.env을 입력합니다.그래서git는 이 파일을 추적하지 않습니다.
  • 라는 이름의 DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority 파일의 새 줄에 변수를 추가합니다
  • .gitignore 파일은 다음과 같습니다.
    DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
    PORT=3000
    
    당신의 .env 파일은 아래와 같습니다
    node_modules
    .env
    
    이제 설치된 패키지.env 파일을 가져옵니다.
    const express = require("express");
    const mongoose = require("mongoose");
    const dotenv = require("dotenv");
    
    이제 환경 변수를 불러오겠습니다.
    dotenv.config({ path: ".env" });
    const PORT = process.env.PORT;
    const dbURI = process.env.DATABASE_URL;
    
    이제 PORT=3000 폴더에 생성된 모델을 가져옵니다.env.
    //model
    const Tasks = require("./models/todos");
    
    이제 .gitignore:
    const connect = mongoose.connect(dbURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    connect.then(
      (db) => {
        console.log("Connected Successfully to Mongodb Server");
    
      },
      (err) => {
        console.log(err);
      }
    );
    
    초기화app.js:
    const app = express();
    
    요청 본문을 json으로 변환하는 todos을 추가합니다.
    app.use(express.json());
    
    마지막으로 특정 포트에서 HTTP 요청을 수신할 탐지기를 만듭니다.
    app.listen(PORT, () => {
      console.log(`Server is running at http://localhost:${PORT}`);
    });
    
    너의 기말고사models/는 이렇게 해야 한다.
     
    const express = require("express");
    const mongoose = require("mongoose");
    const dotenv = require("dotenv");
    
    dotenv.config({ path: ".env" });
    const PORT = process.env.PORT;
    const dbURI = process.env.DATABASE_URL;
    
    //model
    const Tasks = require("./models/todos");
    
    const connect = mongoose.connect(dbURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    connect.then(
      (db) => {
        console.log("Connected Successfully to Mongodb Server");
    
      },
      (err) => {
        console.log(err);
      }
    );
    
    const app = express();
    
    app.use(express.json());
    
    app.listen(PORT, () => {
      console.log(`Server is running at http://localhost:${PORT}`);
    });
    
    이제 우리는 기본database connection 조작을 진행할 수 있다.

    족제비 때 작업


    Mongoose는 유연한 해결 방안express app을 가지고 임무를 완성하는 많은 방법을 제공했다.우리는 이러한 변화를 중점적으로 토론하지 않을 것이다. 왜냐하면 이것은 본고의 범위를 넘어섰기 때문이다. 그러나 대부분의 조작은 여러 가지 방식으로 완성할 수 있고 문법적으로도 가능하며 응용 프로그램 체계 구조를 통해 완성할 수 있다는 것을 명심하세요.

    기록을 세우다


    Dell 데이터베이스middleware에 업무 및 app.js를 입력하십시오.
    let newTask = {
          description: "task added using create",
    };
    
    Tasks.create(newTask)
      .then((data) => {
          console.log(data);
       })
       .catch((err) => {
          console.log(err);
    });
    
    우선, 우리는 CRUD 대상을 만들었는데, 그 중에는 todo의 설명이 포함되어 있으며, todo는 데이터베이스에서 문서를 만드는 데 필요한 필수 필드이다.Mongoose 모델에는 API 방법이 있습니다. 이것은 create 방법입니다. 성공한 후에 우리는 데이터의 응답을 받았습니다. 실패하면 포획되고 오류가 발생합니다.

    모든 작업 찾기


    집합에 저장된 모든 문서입니다.
    //all tasks
    
    Tasks.find({})
       .then((data) => {
           console.log("All tasks", data);
        })
        .catch((err) => {
           console.log(err);
     });
    

    단일 문서 또는 레코드 찾기


    소장품에서 save 문서를 어떻게 찾는지 봅시다.
     //find with condition
    
      Tasks.find({ completed: false })
        .then((data) => {
             console.log("All tasks", data);
         })
         .catch((err) => {
             console.log(err);
        });
    

    문서 업데이트


    기록된 상태newTaskcreate()로 수정
        Tasks.findByIdAndUpdate({ _id: req.params.id },{
                $set: {completed:true},
              },
              { new: true, useFindAndModify: false } //get updated result
           )
           .then((data) => {
             console.log("Updated todo data", data);
           })
           .catch((err) => {
             console.log(err);
           });
    

    컬렉션에서 문서 삭제


     //delete all tasks
         Tasks.remove({});
    
    // delete specific task
    
        Tasks.findByIdAndRemove(task_id)
           .then((data) => {
             console.log("All tasks", data);
           })
           .catch((err) => {
             console.log(err);
           });
    
    상기 예시에서 몬고 DB 데이터베이스에서 작업한 promiseget의 값으로 바꾸면 single처럼 보인다.
    우리는 이미 모든 updating 조작, 즉 completed:false, completed:true, task_id, _id, 5a78fe3e2f44ba8f85a2409a, CRUD를 보았다.create 파일에서 그것들을 사용합니다.
    const express = require("express");
    const mongoose = require("mongoose");
    const dotenv = require("dotenv");
    
    dotenv.config({ path: ".env" });
    const PORT = process.env.PORT;
    const dbURI = process.env.DATABASE_URL;
    
    //model
    const Tasks = require("./models/todos");
    
    const connect = mongoose.connect(dbURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    connect.then(
      (db) => {
        console.log("Connected Successfully to Mongodb Server");
    
        //all tasks
        Tasks.find({})
          .then((data) => {
            console.log("All tasks", data);
          })
          .catch((err) => {
            console.log(err);
          });
    
        // similary use all the other operation here
    
        // CAUTION: don't put all the operation together, use one operation
        // at a time
      },
      (err) => {
        console.log(err);
      }
    );
    
    const app = express();
    
    app.use(express.json());
    
    app.listen(PORT, () => {
      console.log(`Server is running at http://localhost:${PORT}`);
    });
    
    
    이제 다음 명령을 사용하여 read:
    먼저 설치,
    npm install -g nodemon
    
    그리고
    nodemon app.js
    
    update 족제비delete와 Node JS에서 어떻게 사용하는지 알아봤습니다.
    나는 이 문장app.js이 너로 하여금 그 핵심 사상을 이해하게 할 수 있기를 바란다.) 반드시 이 문장serverCongratulations !!의 답안을 주고 나로 하여금 더 많이 쓰게 할 것이다.

    좋은 웹페이지 즐겨찾기