首页 > 解决方案 > 尝试使用 Node 驱动程序重新连接到 mongodb 时出现警告

问题描述

注意:这与NodeJS 驱动程序警告几乎完全相同:选项 [xxxx] is not supported ,类似于Why am I getting this deprecated warning?!MongoDB,除了在我的情况下,我实际上正在关闭使用之间的连接

我要做的是使用 node.js 驱动程序创建一个 db 类,该类可以处理与存储和获取数据相关的所有事情,这样当我开始创建后端时一切都会变得容易得多。我这样做的方式是使用做各种事情的方法。目前我有一个 listDatabases 方法、一个 listCollections 方法和一个 setDatabase 方法。listDatabases 方法连接然后返回 admin.listDatabases(),然后断开连接。listCollections 方法连接,返回 db.collections() 方法和断开连接。setDatabase 方法连接,为数据库对象设置一个变量并返回新数据库的 listCollections() 方法,然后断开连接。

我目前正在通过获取数据库、记录它、然后设置数据库并记录它来测试所有这些。

我得到的错误是:

(node:43816) [MONGODB DRIVER] Warning: the options [servers] is not supported
(node:43816) [MONGODB DRIVER] Warning: the options [caseTranslate] is not supported 
(node:43816) [MONGODB DRIVER] Warning: the options [dbName] is not supported

我第二次尝试做某事时遇到这些错误(在这种情况下是设置数据库)。他们似乎什么也没做,但我查了一下,它说他们可能会产生未知的后果,这让我很害怕。

我在网上发现的一件事是,这可能会发生,因为我的程序在它已经连接时再次连接。我已经确认这不是使用(太多)console.log 的情况,并且在尝试再次连接之前检查它是否已经与 mongoClient.isConnected() 连接。

我的完整代码(我正在使用打字稿):

import { Collection, Cursor, Db, MongoClient } from 'mongodb';
import util from 'util';

interface result<type> {
    result: string;
    code: string;
    data?: type;
}

interface dbListOptions {
    getFullData?: boolean;
}
interface dbListData {
    databases: { name: string; sizeOnDisk: bigint; empty: boolean }[];
    totalSize: bigint;
    ok: bigint;
}

interface colListOptions {
    getFullData?: boolean;
}

class db {
    mongoUrl: string = 'mongodb://127.0.0.1:27017/?retryWrites=true&w=majority';

    mongoOptions: object = { useNewUrlParser: true, useUnifiedTopology: true };

    mongoClient: MongoClient = new MongoClient(
        this.mongoUrl,
        this.mongoOptions
    );

    cursorDatabase?: Db;

    cursorCollection?: Collection;

    cursor?: Cursor;

    constructor(database?: string, collection?: string) {
        if (database) {
            const client = this.mongoClient;
            client.connect().then(() => {
                this.cursorDatabase = client.db(database);
                if (collection) {
                    this.cursorDatabase.collection(
                        collection,
                        { strict: true },
                        (err, col) => {
                            this.cursorCollection = col;
                            client.close();
                        }
                    );
                }
            });
        }
    }

    async connect() {
        if (!this.mongoClient.isConnected()) {
            console.log(this.mongoClient.isConnected());
            await this.mongoClient.connect();
            console.log('Connected');
        }
    }

    async close() {
        if (this.mongoClient.isConnected()) {
            console.log(this.mongoClient.isConnected());
            await this.mongoClient.close();
            console.log('Disconnected');
        }
    }

    async listDatabases(options: dbListOptions = {}) {
        const client = this.mongoClient;
        let result: result<any>;
        try {
            console.log('Pre-Pre-Connect');
            await this.connect();
            console.log('Post-Connect');
            const data: dbListData = await client
                .db('admin')
                .admin()
                .listDatabases();
            result = {
                result: 'SUCCESS',
                code: 'GOT DATABASES',
                data,
            };
        } finally {
            await this.close();
        }
        result ||= { result: 'ERROR', code: 'UNKNOWN ERROR' };
        if (!options.getFullData && result.data) {
            if (!Array.isArray(result.data)) {
                result.data = Array.from(
                    result.data.databases,
                    (obj: { name: string }) => obj.name
                );
            }
        }
        return result;
    }

    get databases() {
        return this.listDatabases();
    }

    async setDatabase(dbName: string, options: colListOptions = {}) {
        const client = this.mongoClient;
        let result: result<Collection[]>;
        try {
            console.log('Pre-Pre-Connect');
            await this.connect();
            console.log('Post-Connect');
            this.cursorDatabase = client.db(dbName);
            const colListResult: result<Collection[]> =
                await this.listCollections();
            const data: Collection[] | undefined = await colListResult.data;
            result = data
                ? {
                        result: 'SUCCESS',
                        code: 'SET DATABASE AND GOT COLLECTIONS',
                        data,
                  }
                : {
                        result: 'ERROR',
                        code: 'COULD NOT GET COLLECTIONS',
                  };
        } finally {
            await this.close();
        }
        result ||= { result: 'ERROR', code: 'UNKNOWN ERROR' };
        if (result.data?.length === 0) {
            result = { result: 'WARN', code: 'DATABASE EMPTY', data: [] };
        }
        return result;
    }

    async listCollections(options: colListOptions = {}, dbName?: string) {
        const client = this.mongoClient;
        let result: result<any>;
        try {
            const database: Db | undefined = dbName
                ? client.db(dbName)
                : this.cursorDatabase;
            if (database) {
                console.log('Pre-Pre-Connect');
                await this.connect();
                console.log('Post-Connect');
                const data: Collection[] = await database.collections();
                result = {
                    result: 'SUCCESS',
                    code: 'GOT COLLECTIONS',
                    data,
                };
            } else {
                result = { result: 'ERROR', code: 'NO DATABASE PROVIDED' };
            }
        } finally {
            await this.close();
        }
        result ||= { result: 'ERROR', code: 'UNKNOWN ERROR' };
        if (!options.getFullData && result.data) {
            if (!Array.isArray(result.data)) {
                result.data = Array.from(
                    result.data.databases,
                    (obj: { name: string }) => obj.name
                );
            }
        }
        return result;
    }
}

(async function () {
    const testdb = await new db();
    const databases: result<dbListData> = await testdb.listDatabases();
    console.log(util.inspect(databases, true, 3));
    const collections: result<Collection[]> = await testdb.setDatabase(
        'storage'
    );
    console.log(util.inspect(collections, true, 2));
})();

标签: node.jsmongodb

解决方案


推荐阅读