关于node.js:Nodejs连接MangoDB之后查找数据返回undefined的问题解决方法

30次阅读

共计 1087 个字符,预计需要花费 3 分钟才能阅读完成。

案例

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);

正文完
 0