본문 바로가기
my_lesson/_NodeJSmongoDB

Mongoose - Getting Started (Schema)

by boolean 2017. 8. 27.
728x90

Getting Started

First be sure you have MongoDB and Node.js installed. Next install Mongoose from the command line using npm:

우선 MongoDB 와 Node.js가 설치되어 있어야하며 명령라인에서 npm을 이용해 Mongoose를 설치한다.

$ npm install mongoose

Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the test database on our locally running instance of MongoDB.

우리가해야 할 첫 번째 일은 프로젝트에 몽구스를 포함시키고 로컬로 실행되는 MongoDB의 인스턴스에서 테스트 데이터베이스에 대한 연결을 여는 것입니다. 해당 프로젝트 아래에 models 폴더를 만들고 

// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testDB');

We have a pending connection to the test database running on localhost. We now need to get notified if we connect successfully or if a connection error occurs:

성공적으로 연결했거나 연결 오류가 발생하면 알림을 받아야합니다.

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

Once our connection opens, our callback will be called. 

연결이 되면 콜백이 호출됩니다.

For brevity, let's assume that all following code is within this callback.

간결하게하기 위해 다음의 모든 코드가 이 콜백 내에 있다고 가정 해 봅시다.

With Mongoose, everything is derived from a Schema.

Mongoose를 사용하면 모든 것이 스키마에서 파생됩니다.

Let's get a reference to it and define our kittens.

그것에 대한 참고를 하고 새끼 고양이를 정의합시다.

var kittySchema = mongoose.Schema({
    name: String
});

So far so good. 

여태까지는 그런대로 잘됐다.

We've got a schema with one property, name, which will be a String

우리는 하나의 속성 name을 가진 스키마를 가지고 있는데, 이것은 String이 될 것입니다.

The next step is compiling our schema into a Model.

다음 단계는 스키마를 모델로 컴파일하는 것입니다.

var Kitten = mongoose.model('Kitten', kittySchema);

A model is a class with which we construct documents. 

모델은 문서를 구성하는 클래스입니다.

In this case, each document will be a kitten with properties and behaviors as declared in our schema. 

이 경우 각 문서는 우리의 스키마에 선언 된 속성 및 동작을 가진 새끼 고양이가됩니다.

Let's create a kitten document representing the little guy we just met on the sidewalk outside:

우리가 방금 길가에서 만난 작은 녀석을 대표하는 새끼 고양이 문서를 만들어 봅시다 :

var silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'

Kittens can meow, so let's take a look at how to add "speak" functionality to our documents:

새끼 고양이는 야옹 할 수 있으므로 문서에 "말하기"기능을 추가하는 방법을 살펴 보겠습니다.

// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
  var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name";
  console.log(greeting);
}

var Kitten = mongoose.model('Kitten', kittySchema);

Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:

스키마의 methods 속성에 추가 된 함수는 Model 프로토 타입으로 컴파일되고 각 문서 인스턴스에 노출됩니다.

var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"

We have talking kittens! 

우리는 새끼 고양이 이야기!

But we still haven't saved anything to MongoDB. 

그러나 우리는 여전히 MongoDB에 아무것도 저장하지 않았습니다. 

Each document can be saved to the database by calling its save method. 

각 문서는 save 메소드를 호출하여 데이터베이스에 저장할 수 있습니다. 

The first argument to the callback will be an error if any occured.

콜백에 대한 첫 번째 인수는 오류가 발생한 경우 인수입니다.

fluffy.save(function (err, fluffy) {
  if (err) return console.error(err);
  fluffy.speak();
});

Say time goes by and we want to display all the kittens we've seen. 

지난 시간동안 우리가 본 모든 새끼 고양이를 표시하고 싶습니다.

We can access all of the kitten documents through our Kitten model.

 우리는 Kitten 모델을 통해 모든 새끼 고양이 문서에 액세스 할 수 있습니다.

Kitten.find(function (err, kittens) {
  if (err) return console.error(err);
  console.log(kittens);
})

We just logged all of the kittens in our db to the console. 

우리는 db에있는 모든 새끼 고양이를 콘솔에 기록했습니다. 

If we want to filter our kittens by name, Mongoose supports MongoDBs rich querying syntax.

우리가 새끼 고양이를 이름으로 걸러 내고 싶다면 Mongoose는 MongoDB의 풍부한 쿼리 문법을 지원합니다.

Kitten.find({ name: /^fluff/ }, callback);

This performs a search for all documents with a name property that begins with "Fluff" and returns the result as an array of kittens to the callback.

그러면 "Fluff"로 시작하는 이름 속성을 가진 모든 문서를 검색하고 그 결과를 콜백에 새끼들의 배열로 반환합니다.

JS Bin on jsbin.com

Congratulations

That's the end of our quick start. 

이것이 우리의 퀵 스타트의 끝입니다.

We created a schema, added a custom document method, saved and queried kittens in MongoDB using Mongoose.

 우리는 Mongoose를 사용하여 MongoDB에 스키마를 만들고, 사용자 정의 문서 메소드를 추가하고, 고양이를 저장하고 쿼리했습니다.

 Head over to the guide, or API docs for more. 

가이드 또는 API 문서를 참조하십시오.

'my_lesson > _NodeJSmongoDB' 카테고리의 다른 글

create-react-app +react-hot-loader 사용하기  (0) 2017.10.21
React +Express + Node JS  (0) 2017.09.13
Atom -기본 사용법 shortcuts sftp단축키 필수packages  (1) 2017.09.07
Node JS  (0) 2017.08.29
Mongodb  (0) 2017.08.26

댓글