Nodejs mongodb 连接的问题

Nodejs mongodb 连接的问题

刚接触 node 准备用来做内部的web 工具 按照大部分教程 在连接 mongodb 的时候 都是 类似 mongodb.open(function (err, db) { if (err) { return callback(err); } db.collection(’’, function (err, collection) { if (err) { mongodb.close(); return callback(err); } collection.findOne( db.close() }); });

先open 在 collection 最后 再 close 用的时候发现有问题 一次处理多个插入的时候 容易报错 候来看mongo 官方的 已经不是这样做了

var MongoClient = require(‘mongodb’).MongoClient , format = require(‘util’).format;

MongoClient.connect(‘mongodb://127.0.0.1:27017/test’, function(err, db) { if(err) throw err;

var collection = db.collection('test_insert');
collection.insert({a:2}, function(err, docs) {

collection.count(function(err, count) { console.log(format(“count = %s”, count)); });

// Locate all the entries using find collection.find().toArray(function(err, results) { console.dir(results); // Let’s close the db db.close(); });
});

}) 这个是官方的 我在connect 回调 里面 拿到 db 后 放在了全局里面 再也没有 close 过 就好了 不知道大家遇到过没有


4 回复

当然可以。以下是如何使用 Node.js 和 MongoDB 进行连接并执行一些基本操作的详细说明和示例代码。

问题描述

在早期的教程中,通常会使用 mongodb.open 方法来连接数据库,并在每次操作完成后关闭数据库连接。但在处理大量数据或并发请求时,这种方法可能会导致错误。MongoDB 官方推荐的方式是使用 MongoClient.connect 方法来管理连接,该方法更灵活且适用于现代应用的需求。

示例代码

// 引入必要的模块
const { MongoClient } = require('mongodb');
const util = require('util');

// MongoDB 连接字符串
const uri = 'mongodb://127.0.0.1:27017/test';

// 使用 MongoClient.connect 方法连接到 MongoDB
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(client => {
    console.log('Connected to Database');
    
    const db = client.db(); // 获取数据库实例
    const collection = db.collection('test_insert'); // 获取集合实例
    
    // 插入文档
    collection.insertOne({ a: 2 })
      .then(result => {
        console.log(`A document was inserted with the _id: ${result.insertedId}`);
        
        // 查询所有文档并打印
        return collection.find().toArray();
      })
      .then(results => {
        console.log('Found the following records');
        console.dir(results);
        
        // 关闭数据库连接
        return client.close();
      })
      .catch(error => {
        console.error(error);
        client.close(); // 如果发生错误,确保关闭连接
      });
  })
  .catch(error => {
    console.error(error);
  });

解释

  1. 引入模块

    • mongodb 包中的 MongoClient 用于连接 MongoDB。
    • util 包中的 format 方法用于格式化输出。
  2. 连接到 MongoDB

    • 使用 MongoClient.connect 方法连接到 MongoDB 数据库。useNewUrlParseruseUnifiedTopology 是为了确保兼容性。
  3. 操作数据库

    • 获取数据库实例 client.db() 和集合实例 db.collection('test_insert')
    • 使用 insertOne 方法插入一个文档。
    • 使用 find().toArray() 方法查询所有文档并打印。
  4. 关闭连接

    • 在所有操作完成后,使用 client.close() 关闭数据库连接。如果发生错误,则在捕获错误时也关闭连接以避免资源泄漏。

这种方式更加高效和可靠,特别是在处理高并发请求时。希望这能帮助你解决连接 MongoDB 的问题。


报错是因为db操作是异步的 可能是还没有close的时候又open了一下 保持一个全局的db连接也不会占太多的内存 反而是一会close一会open延时会提高不少吧 大型应用的话会保持一个数据库连接池的

恩对的我就是这个意思,教程中没有就这个展开来说 估计好多新手都是按照教程来做的 而且mongo 官方示例中已经没有了open操作在获取 collection对象的时候也不是在回调函数里面 var collection = db.collection(‘test_insert’);

根据你的描述,你在使用 Node.js 连接 MongoDB 时遇到了一些问题。你提到使用 mongodb.open 方法时,在处理多条插入操作时容易出错。为了解决这个问题,你可以使用官方推荐的方式连接 MongoDB,这种方式更加现代化且更易于管理数据库连接。

示例代码

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

async function run() {
    const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        console.log("Connected to MongoDB");

        const database = client.db('test');
        const collection = database.collection('test_insert');

        // 插入数据
        await collection.insertOne({ a: 2 });
        
        // 查询数据
        const count = await collection.countDocuments({});
        console.log(`Count = ${count}`);

        const documents = await collection.find().toArray();
        console.dir(documents);

    } catch (error) {
        console.error("Error occurred:", error);
    } finally {
        await client.close();
        console.log("Disconnected from MongoDB");
    }
}

run().catch(console.error);

解释

  1. 异步处理:使用 async/await 来处理异步操作,这使得代码更清晰且更容易阅读。
  2. 连接数据库:通过 client.connect() 连接到 MongoDB,而不是使用 mongodb.open
  3. 操作数据库:在连接成功后,你可以直接对数据库进行操作,如插入数据、查询数据等。
  4. 错误处理:在 try/catch 块中捕获并处理可能发生的错误。
  5. 关闭连接:在所有操作完成后,确保调用 client.close() 关闭数据库连接。

这种方式不仅更现代,而且可以更好地处理并发操作,避免因连接管理不当导致的问题。希望这能帮助你解决问题!

回到顶部