Nodejs连接MangoDB之后查找数据返回undefined的问题解决方法

RyanWu -
Nodejs连接MangoDB之后查找数据返回undefined的问题解决方法
案例
const { MongoClient } = require('mongodb')

async function main(){
    const url = "mongodb://localhost:27017"
    const client = new MongoClient(url);
    const dbName = 'my-react-admin'
    try {
        await client.connect();
        console.log('Access to database!')
        const db = client.db(dbName);
        db.collection('users').find({}).toArray((err, data) => {
            // if (err) throw err
            console.log(data)
        })
    } catch (e) {
        console.error(e);
    } 
    finally {
        await client.close();
    }
}
main().catch(console.error);

这样写出来运行,输出的是

Access to database!
undefined

也就是说,其实连接上了数据库但是没返回东西。
然后加上一个throw err看看到底哪里出了问题
再次运行,报错了

MongoExpiredSessionError: Cannot use a session that has ended

发现是因为异步操作的问题导致在数据库断开连接之前并没有进行数据查询,也就是查数据那一步并没有进行异步操作,而在Array里面传入回调函数是没法返回Promise对象的,所以也没法添加await。
删除回调函数之后,再添加await输出,即可解决这个问题。

const { MongoClient } = require('mongodb')
const url = "mongodb://localhost:27017"
const client = new MongoClient(url);

async function main(){
    const dbName = 'my-react-admin'
    try {
        await client.connect();
        console.log('Connect to database!')
        const db = client.db(dbName);
        const result = await db.collection('users').find({}).toArray()
        console.log(result)
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}
main().catch(console.error);
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

node.jsmongodb

扩展阅读

加个好友,技术交流

1628738909466805.jpg