mongoose의 싱글톤 패턴

    ▲ 그림 1-4 MongoDB 로고

    실제로 싱글톤 패턴은 Node.js에서 MongoDB 데이터베이스를 연결할 때 쓰는 mongoose 모듈에서 볼 수 있습니다.

    mongoose의 데이터베이스를 연결할 때 쓰는 connect()라는 함수는 싱글톤 인스턴스를 반환합니다. 다음은 connect() 함수를 구현할 때 쓰인 실제 코드입니다.

     

    자바스크립트

    Mongoose.prototype.connect = function(uri, options, callback) {
        const _mongoose = this instanceof Mongoose ? this : mongoose;
        const conn = _mongoose.connection;
    
        return _mongoose._promiseOrCallback(callback, cb => {
            conn.openUri(uri, options, err => {
                if (err != null) {
                    return cb(err);
                }
                return cb(null, _mongoose);
            });
        });
    };
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.