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