Nodejs db object already connecting, open cannot be called multiple times

Nodejs db object already connecting, open cannot be called multiple times

新学mongodb 出现这个问题 看了网上的文章 但是有没有解决这个问题的好方法 求大神指导

7 回复

Node.js db object already connecting, open cannot be called multiple times

当你在使用 Node.js 和 MongoDB 进行开发时,可能会遇到一个常见的问题:当你尝试多次调用数据库连接函数(例如 open)时,会收到错误信息 “db object already connecting, open cannot be called multiple times”。这是因为 MongoDB 的驱动程序不允许你重复打开同一个连接。

问题描述

假设你在应用程序启动时初始化了一个 MongoDB 连接,并且在多个地方尝试重新打开这个连接。这会导致上述错误。

解决方案

为了避免这种情况,你需要确保只在一个地方初始化并管理数据库连接。你可以使用一个全局变量来存储连接对象,并在需要时检查该连接是否已经打开。

示例代码

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
let db;

async function connectToDatabase() {
    if (!db) {
        try {
            db = await MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
            console.log("Connected to MongoDB");
        } catch (error) {
            console.error("Failed to connect to MongoDB", error);
        }
    } else {
        console.log("Already connected to MongoDB");
    }
}

// 使用示例
async function main() {
    await connectToDatabase();
    
    // 假设你需要执行一些数据库操作
    const collection = db.collection('exampleCollection');
    const result = await collection.find({}).toArray();
    console.log(result);
}

main().catch(console.error);

解释

  • connectToDatabase 函数负责连接到 MongoDB 数据库。
  • 我们使用一个全局变量 db 来存储连接对象。
  • connectToDatabase 函数中,我们首先检查 db 是否已经存在。如果不存在,则尝试建立一个新的连接。
  • 如果连接成功,我们将连接对象赋值给 db 变量。
  • 如果连接已经存在,我们会输出一条消息,表示已经连接到 MongoDB。

通过这种方式,你可以确保在整个应用程序生命周期中只创建一次数据库连接,避免了重复调用 open 方法导致的错误。


用mongoose

忘记close了。。。。

连接一次就行了,不要多次连接

求详细,我的代码: db.open(function(err,client){ if(err) { response.write(’{err: 1, msg: “数据库出错”}’); response.end(); } var collection=new mongodb.Collection(client,‘user’);

                    collection.find({name:get.user}).toArray(function(err,data){
                            if(data.length>0){
                                response.write('{err: 1, msg:用户名存在}');
                                response.end();
                                console.log(doc);
                            }else{
                                collection.insert({name:get.user,pass:get.pass},{safe:true},function(err, data){
                                    if(err){
                                        response.write('{err: 1, msg: "数据库出错"}');
                                        response.end();
                                    }
                                    response.write('{err: 0, msg:注册成功}');
                                    response.end();
                                });
                            }
                    });
                });

// Establish connection to db db.open(function(err, db) { if(err) { return callback(err); }

// Authenticate
db.authenticate('<username>', '<pwd>', function(err, result) {
  if(result) {
    // Fetch a collection
    db.collection('<collection>', function(err, collection) {
      if(err) {
        // Close db connection
        db.close();
        return callback(err);
      }
  collection.insert(entity, {safe: true}, function(err, result) {
    // Close db connection
    db.close();
    callback(err, result);
  });
});

} else { // Close db connection db.close(); callback(utils.error(‘Auth Error’)); } });

}); 给你看看我以前写过的吧,你应该是之前在打开数据库连接的时候,之后忘记close了

当你遇到“db object already connecting, open cannot be called multiple times”的错误时,这通常是因为你在同一个数据库对象上尝试多次调用 .open() 方法。MongoDB 的 Node.js 驱动程序(如 mongodb 包)不支持重复连接到同一个数据库实例。你需要确保只创建一个数据库连接,并在整个应用程序中重用它。

以下是一些解决方案:

解决方案

1. 使用单例模式

确保你只有一个数据库连接。你可以通过使用单例模式来实现这一点。

const { MongoClient } = require('mongodb');

class Database {
    constructor() {
        this.connection = null;
    }

    async connect() {
        if (this.connection) {
            return this.connection;
        }

        const url = 'mongodb://localhost:27017';
        const dbName = 'myproject';

        const client = new MongoClient(url);
        await client.connect();
        console.log("Connected correctly to server");

        this.connection = client.db(dbName);
        return this.connection;
    }
}

const db = new Database();

// 在其他地方使用
(async () => {
    const myDb = await db.connect();
    // 在这里执行你的数据库操作
})();

2. 使用全局变量或模块

你也可以将数据库连接存储在一个全局变量或模块中。

const { MongoClient } = require('mongodb');

let dbConnection;

async function connectToDatabase() {
    if (dbConnection) {
        return dbConnection;
    }

    const url = 'mongodb://localhost:27017';
    const dbName = 'myproject';

    const client = new MongoClient(url);
    await client.connect();
    console.log("Connected correctly to server");

    dbConnection = client.db(dbName);
    return dbConnection;
}

// 在其他地方使用
(async () => {
    const myDb = await connectToDatabase();
    // 在这里执行你的数据库操作
})();

总结

确保你的数据库连接只被初始化一次,并且在整个应用中重用这个连接。通过上述方法,你可以避免重复调用 .open() 导致的错误。这样可以保证你的应用更加高效和稳定。

回到顶部