Mongoose ODM(Object Data Modeling)
MongdoDB의 Collection에 집중하여 관리하도록 도와주는 패키지
Collection을 모델화하여, 관련 기능들을 쉽게 사용할 수 있도록 도와준다.
Join
기능을 MongoDB에서 제공하지 않지만, Mongoose는 이와 유사한 기능인 Populate를 사용하여 간단하게 구현할 수 있다.다영한 형식을 미리 지정하여, 생성 및 수정 작업 시 데이터 형식을 체크해주는 기능을 제공한다.
timestamps
옵션을 사용하면 생성, 수정 시간을 자동으로 기록해준다.
작성된 스키마를 mongoose에서 사용할 수 있는 모델로 만들어야 한다.
모델의 이름을 지정하여 Populate등에서 해당 이름으로 모델을 호출 할 수 있다.
connect
함수를 이용하여 간단하게 데이터베이스에 연결할 수 있다.
mongoose는 자동으로 연결을 관리해줘서 직접 연결 상태를 체크하지 않아도 모델 사용 시 연결 상태를 확인하여 사용이 가능할 때 작업을 실행한다.
작성된 모델을 이용하여 CRUD를 수행할 수 있다.
-create
-find, findById, findOne
-updateOne, updateMany, findByIdAndUpdate, findOneAndUpdate
-deleteOne, deleteMany, findByIdAndDelete, findOneAndDelete
**참고로, update 관련 함수(updateOne, updateMany)는 update된 결과를 리턴하고,
find 관련 함수(findByIdAndUpdate, findOneAndUpdate)는 검색된 결과에 업데이트가 반영된 내용을 리턴한다.
이러한 로직은 delete와 관련된 함수도 동일하다.
Document 안에 Document를 담지 않고, OnjectID를 가지고 reference하여 사용할 수 있는 방법을 제공한다.
Document에는 reference되는 ObjectID를 담고, 사용할 때 populate하여 하위 Document처럼 사용할 수 있게 해준다.
-사용예제
const Post = new Schema({
..
user:{
type: Schema.Types.ObjectId,
ref: 'User',
},
comments:[{
type: Schema.Types.ObjectId,
ref: 'Comment',
}],
});
const post = await Post.find().populate(['user', 'comments']);
//post.user.name, post.comments[0].content
mongoose.connect('---');
mongoose.connect.on('connected', ()=>{
});
mongoose.connect.on('disconnected', ()=>{
});
mongoose.connect.on('reconnected', ()=>{
});
mongoose.connect.on('reconnectFailed', ()=>{
});