Node JS 및 MongodB Atlas를 사용하여 CRUD 애플리케이션 구축
13915 단어 nodemongodbcodenewbiebeginners
본고에서 우리는
MongoDB
usingNode JS
library에서 Mogoose
데이터베이스를 어떻게 사용하는지 배울 것이다. 이것은 업계에서 광범위하게 사용되는 매우 유행하는 라이브러리이다.In this article we had used the
MongoDB Cloud
service called MongoDB Atlas, you can also use the MongoDB server runninglocally
, 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을 사용하는 장점 중 하나입니다. 왜냐하면 응용 프로그램 개발을 가속화하고 배치의 복잡성을 낮추기 때문입니다.다음은 데이터가
Mongo
및 SQL
데이터베이스에 저장되는 방법의 예입니다.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 에서 더 많은 정보를 볼 수 있고, 또한 필수 필드이기 때문에 키 required
와 boolean
값true로 정의했습니다.모드에 더 많은 필드를 추가하고,
const todoSchema = new Schema(
{
description: {
type: String,
required: true,
},
completed: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
마찬가지로, Boolean 형식이고 기본값false가 있는 completed
필드를 정의했습니다.구조를 자세히 살펴보면 두 번째 파라미터가 전달됩니다. 이것은 키가 있는 대상
timestamps
이기 때문에 두 번째 파라미터는 설정 대상입니다. 우리는 몬고우스의 내장 기능만 사용했고 문서마다 추가 필드, 즉 createdAt
와 updatedAt
를 추가했습니다.다음을 허용합니다
Schema Types
.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-mongoose
express 설치npm init -y
족제비 설치app.js
dotenv 설치npm install express
라는 파일을 만듭니다.npm install mongoose
는 다음과 같다.npm install dotenv
app.js
파일database url
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);
});
문서 업데이트
기록된 상태
newTask
를 create()
로 수정 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 데이터베이스에서 작업한 promise
을 get
의 값으로 바꾸면 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
이 너로 하여금 그 핵심 사상을 이해하게 할 수 있기를 바란다.) 반드시 이 문장server
에 Congratulations !!
의 답안을 주고 나로 하여금 더 많이 쓰게 할 것이다.
Reference
이 문제에 관하여(Node JS 및 MongodB Atlas를 사용하여 CRUD 애플리케이션 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ialtafshaikh/building-a-crud-application-using-node-js-and-mongodb-atlas-2df5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)