0

当我尝试关闭 NodeJS 和 MongoDB 集群之间的连接时,我得到 mongoClient.close 不是一个函数。请帮忙

节点 JS MongoDB 代码

const mongoClient = require("mongodb").MongoClient;

exports.getInfo = async (czytnik_id) => {
    return new Promise((resolve, reject) => {
        mongoClient.connect(process.env.URI, { useUnifiedTopology: true }, (err, db) => {
            if (err) reject(err);
            const dbo = db.db('TTI');
            const res = dbo.collection('3P').findOne({ id: czytnik_id });
            mongoClient.close()
            resolve(res);
        });
    });
}
4

2 回答 2

1

根据docs,回调 inMongoClient.connect()接受一个错误和一个连接的客户端实例,这是要关闭的。在你的情况下,它似乎是db,所以尝试db.close()而不是mongoClient.close().

于 2022-02-07T09:46:06.003 回答
0

来自 doc mongodb - npm and Connection guideMongoClient是一个类。您需要创建一个客户端实例,该.close方法是一个实例方法。

例子:

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

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

// Database Name
const dbName = 'myProject';

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('documents');

  // the following code examples can be pasted here...

  return 'done.';
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());
于 2022-02-17T04:25:25.493 回答