Mongoose 다중 연결 시 링크 별 Model 사용 방법

2022. 2. 11. 18:19MongoDB, Mongoose

Mongoose 다중 연결 방법 : https://crispypotato.tistory.com/182

 

Mongoose 다중 connect 연결 방법

한개 connection 연결방법 : https://crispypotato.tistory.com/25 connection 링크를 여러개 연결해야 하는 경우 connection을 다중으로 만들어서 연결을 만들면 에러가 발생한다. 해결 방법 * 주요 * mongoose...

crispypotato.tistory.com

 

다중 연결 후 같은 모델을 사용하지만 링크가 다른 경우 

기존에는 mongoose 바로 require 했지만 

다중 연결에서는 사용 할 connection에 Model을 넣어 주어야 한다.

 

테스트 링크를 사용하는 model은 testUser: mongoose.test.model('User', UserSchema)

실제 사용하는 model은 User: mongoose.product.model('User', UserSchema) 로 분리 하여 각각 사용이 가능하다.

 

const conn = require('../db/db').connect
const mongoose = conn()
const Schema = mongoose.Schema

const UserSchema = new Schema({
  name: { type: String, required: true },
  id: { type: String, unique: true },
  password: { type: String, required: true },
  nickName: { type: String, default: '' }
})

module.exports = {
  testUser: mongoose.test.model('User', UserSchema),
  User: mongoose.product.model('User', UserSchema)
}

 

728x90
반응형