mongodb MongoBulkWriteError:试图从已关闭的连接池中 checkout 连接

rlcwz9us  于 2023-05-17  发布在  Go
关注(0)|答案(1)|浏览(180)

我想在mongodb数据库中插入nodejs文件中的一些数据。但是我得到如下的错误消息。我该怎么做?我基本上是Mongodb和NodeJS的初学者。我在stackoverflow上搜索了一些文档和帖子,但没有一个对我有用。

const {
  MongoClient
} = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'fruitsDB';

async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server!!!!');
    const db = client.db(dbName);
    const collection = db.collection('fruits');

    // the following code examples can be pasted here...
    collection.insertMany([
        {
          name: "Apple",
          score: 8,
          review: "Great fruit"
        },
        {
          name: "Orange",
          score: 6,
          review: "Kinda sour"
        }
      ])

      return 'done.';
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

这是我执行的命令。

$ FruitsProject % node app.js

这是我终端上的信息。

Connected successfully to server!!!!
done.
/Users/xxxxxx/Desktop/FruitsProject/node_modules/mongodb/lib/bulk/common.js:330
            return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult)));
                            ^

MongoBulkWriteError: Attempted to check out a connection from closed connection pool
    at resultHandler (/Users/xxxxxx/Desktop/FruitsProject/node_modules/mongodb/lib/bulk/common.js:330:29)
    at /Users/xxxxxx/Desktop/FruitsProject/node_modules/mongodb/lib/utils.js:282:66
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  address: '127.0.0.1:27017',
  writeErrors: [],
  result: BulkWriteResult {
    insertedCount: 0,
    matchedCount: 0,
    modifiedCount: 0,
    deletedCount: 0,
    upsertedCount: 0,
    upsertedIds: {},
    insertedIds: {
      '0': ObjectId {
        [Symbol(id)]: Buffer(12) [Uint8Array] [
          100,  91, 252, 154, 95,
           37,  33,  75, 234, 61,
           96, 249
        ]
      },
      '1': ObjectId {
        [Symbol(id)]: Buffer(12) [Uint8Array] [
          100,  91, 252, 154, 95,
           37,  33,  75, 234, 61,
           96, 250
        ]
      }
    }
  },
  [Symbol(errorLabels)]: Set(0) {}
}

Node.js v18.15.0
qmb5sa22

qmb5sa221#

我对MongoDB不太熟悉,但也许你必须在返回'done'之前await插入。
试试这个:

await collection.insertMany([ .....

相关问题