如何修复MongoError:无法使用已结束的会话 [英] How to fix MongoError: Cannot use a session that has ended

查看:141
本文介绍了如何修复MongoError:无法使用已结束的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Node.js从MongoDB Atlas集合中读取数据.当我尝试读取集合的内容时,出现错误MongoError: Cannot use a session that has ended.这是我的代码

I'm trying to read data from a MongoDB Atlas collection using Node.js. When I try to read the contents of my collection I get the error MongoError: Cannot use a session that has ended. Here is my code

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

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

我可以查询特定的文档,但是我不确定如何返回集合的所有文档.我已经搜索了此错误,但找不到很多错误.谢谢

I'm able to query for a specific document, but I'm not sure how to return all documents of a collection. I've searched for this error, I can't find much on it. Thanks

推荐答案

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

In your code, it doesn't wait for the find() to complete its execution and goes on to the client.close() statement. So by the time it tries to read data from the db, the connection has already ended. I faced this same problem and solved it like this:

// 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函数中.

this whole thing should be in an async function.

这篇关于如何修复MongoError:无法使用已结束的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆