gpt4 book ai didi

node.js - 如何修复 MongoError : Cannot use a session that has ended

转载 作者:行者123 更新时间:2023-12-03 07:38:31 24 4
gpt4 key购买 nike

我正在尝试使用 Node.js 从 MongoDB Atlas 集合中读取数据。当我尝试读取集合的内容时,出现错误MongoError:无法使用已结束的 session 。这是我的代码

client.connect(err => {
const collection = client
.db("sample_airbnb")
.collection("listingsAndReviews");

const test = collection.find({}).toArray((err, result) => {
if (err) throw err;
});
client.close();
});

我能够查询特定文档,但我不确定如何返回集合的所有文档。我已经搜索过这个错误,但找不到太多相关信息。谢谢

最佳答案

在您的代码中,它不会等待 find() 完成执行,而是继续执行 client.close() 语句。因此,当它尝试从数据库读取数据时,连接已经结束。我遇到了同样的问题并这样解决:

// connect to your cluster
const client = await MongoClient.connect('yourMongoURL', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// specify the DB's name
const db = client.db('nameOfYourDB');
// execute find query
const items = await db.collection('items').find({}).toArray();
console.log(items);
// close connection
client.close();

编辑:这整个事情应该在一个async函数中。

关于node.js - 如何修复 MongoError : Cannot use a session that has ended,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com