ClientSession требует наличия ServerSessionPool в репликационной базе Mongdb - NODEJS - PullRequest
0 голосов
/ 15 января 2020

Я получил следующую ошибку о наборе реплик mon go и не нашел никаких документов об этом

ClientSession requires a ServerSessionPool

У меня есть несколько служб nodejs, использующих драйвер узла MongoDB .

Кто-нибудь имеет представление, в чем может быть ошибка?

Error: ClientSession requires a ServerSessionPool\n at new ClientSession (/app/node_modules/mongodb/lib/core/sessions.js:73:13)\n at ReplSet.startSession (/app/node_modules/mongodb/lib/topologies/topology_base.js:268:21)\n at executeOperation (/app/node_modules/mongodb/lib/operations/execute_operation.js:49:26)\n at Collection.<anonymous> (/app/node_modules/mongodb/lib/collection.js:1096:12)\n at Collection.deprecated [as findOne] (/app/node_modules/mongodb/lib/utils.js:621:17)\n at

У меня установлено 3 реплики на основе следующего репо: https://github.com/bitnami/bitnami-docker-mongodb

мой мон go класс подключения:

import { MongoClient } from 'mongodb'
import fs from 'fs'

export default class MongoService {
    constructor({ loggerFactory, configService }) {
        const mongoConf = configService.get('mongo')
        this.logger = loggerFactory.logger
        if(mongoConf != null) {
            this.mongoUrlFixed = configService.get('mongo.url')
            this.mongoNodeName = configService.get('mongo.mongo_node_name')
            this.mongoDbName = configService.get('mongo.mongo_db_name')
            this.logger.info('Mongodb configuration found')
        }
        this.configService = configService
    }

    async getConnection() {
        if(!this.mongoUrlFixed) {
            throw new Error('mongo is not configured for this service')
        }
        if(!this.conn) {
            let password_file_path = this.configService.get('mongo.mongo_user_password_file')
            let username = this.configService.get('mongo.mongo_user_username')

            if (fs.existsSync(password_file_path)) {
                let password = fs.readFileSync(password_file_path, 'utf8').replace(/\n$/, '')
                this.mongoUrl = `mongodb://${username}:${password}@${this.mongoNodeName}/${this.mongoDbName}?${this.mongoUrlFixed}`
            }
            try{
                await this.waitForMongo({timeout: 1000 * 60 * 2})

            } catch (err) {
                this.logger.error('An error occured while connecting to mongodb', err)
                process.exit(1)
            }
        }
        return this.conn
    }

    async waitForMongo(options) {
        return new Promise((resolve, reject) => {
            let timeouted = false 
            let timeoutHandler = setTimeout(() => {
                timeouted = true
                reject('TIMEOUTED_WAIT_FOR_MONGO')
            }, options.timeout) 

            let repeat = () => {
                setTimeout(async () => {
                    if(timeouted) return
                    try {
                        if(!this.mongoUrl)
                            this.conn = await MongoClient.connect(this.mongoUrlFixed, { useNewUrlParser: true })
                        else
                            this.conn = await MongoClient.connect(this.mongoUrl, { useNewUrlParser: true })
                    } catch (err) {
                        this.logger.debug('hanven\'t connected yet to mongodb', err)
                    }
                    if(!this.conn) {
                        setTimeout(repeat, 2000)
                    } else {
                        clearTimeout(timeoutHandler)
                        timeoutHandler = null
                        process.on('SIGINT', () => {
                            if(this.conn)
                                this.conn.close()
                        })
                        resolve()
                    }
                }, 2000) 
            }
            repeat()
        })
    }
}

1 Ответ

0 голосов
/ 16 января 2020

Хорошо, после такого рода исследований я нашел решение:

1 - обновить диск узла MongoDB 3.5.0 2 - добавить {useUnifiedTopology: true}

Читайте об использованииUnifiedTopology здесь:

https://mongoosejs.com/docs/deprecations.html

и

https://github.com/mongodb/node-mongodb-native/releases/tag/v3.3.0

...