티스토리 뷰

연습

[MongoDB] Mongoose Schema Statics/Method

onaeonae1 2021. 1. 29. 21:37

들어가는 글

Mongosoe 는 MongoDB의 ODM(Object-Document Mapper) 라이브러리이다.

간단하게 JS의 객체와 Mongoose의 Document를 매핑해준다고 이해할 수 있다.

 

mongoosejs.com/

 

Mongoose ODM v5.11.14

Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose. const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology:

mongoosejs.com

Schema?

MongoDB는 NoSQL인데, 관계형의 Schema 개념이 필요할 때가 있다.

Mongoose 에서는 이를 지원한다.

이 Schema는 MongoDB에서는 collection으로 연결된다고 이해할 수 있다.

mongoosejs.com/docs/guide.html

 

Mongoose v5.11.14: Schemas

Schemas If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the migration guide. Everything in Mongoose starts with a Schema. Each s

mongoosejs.com

 

Schema 설정

스키마에 여러 필드들을 정의할 수 있고 그들에 대한 옵션을 정의해줄 수 있다.

import mongoose from 'mongoose';

const ChatSchema = new mongoose.Schema({
  message: {
    type: String,
    required: 'message is required',
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  speaker: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  joiningRoom: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Room',
  },
});
const model = mongoose.model('Chat', ChatSchema);
export default model;

여러 필드들과 그의 타입, 기타 옵션등을 정의해줄 수 있다.

위의 타입들 외에 다양한 타입들을 정의해줄 수 있는데, 이는 mongoose Schema Types 문서를 살펴보는게 좋다.

mongoosejs.com/docs/schematypes.html

 

Mongoose v5.11.14: SchemaTypes

SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries, and other general characteristics for Mongoose document properties. You can think of a Mongoose schema as the configuration object for a Mon

mongoosejs.com

 

Schema Statics/ (Instance) Method

정확하게는

스키마 Statics, Methods는 스키마와 관련 있는 함수라고 생각하면 된다.

각각 this를 통해 Schema 자체 / Document 하나 에 대해 접근한다. 따라서 화살표 함수를 사용하지 않는다.

UserSchema.methods.addFriend = async function (friendId) {
  if (this.friendsList.includes(friendId)) {
    return false;
  }
  this.friendsList.push(friendId);
  await this.save();
  return true;
};

위의 함수는 schema method이다.

이때 this는 UserSchema 의 Document 하나를 의미한다.

UserSchema.statics.findByEmail = async function (email) {
  const result = await this.findOne({ email });
  return result;
};

위의 함수는 schema static이다.

이때 this는 UserSchema 전체. 즉 User Collection 전체를 의미한다.

 

이러한 Static/Method 들을 적절하게 사용해서 관리하기 편한 코드를 짤 수 있겠다.

 

 

개인적인 견해

해당 내용을 알기 전에는 controller에서 직접 모델을 바로바로 건드려줬는데,  현재로서는 DB를 직접적으로 조작 혹은 데이터가 valid 한지 검사할 때 이러한 스키마에서 미리 정의한 statics, method들을 통해 사용하도록 구현하고 있다.

 

공식 문서를 제대로 읽고 사용할 수 있도록 노력해야겠다.

 

출처

mongoose document

 

Mongoose v5.11.14: Schemas

Schemas If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the migration guide. Everything in Mongoose starts with a Schema. Each s

mongoosejs.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함