const connect = async () => {
// 连接 mongodb 数据库
const db = await monguaDb()
const collection = db.collection('user')
let b = await collection.find({}).toArray()
cc = b
console.log("111---" , cc)
return b
}
const a = connect()
console.log("2222--------", cc)
As the title says, I want to encapsulate mongo into Model.... But I found a problem. There is no problem with printing inside, but when calling outside, the data will be lost. . . . 222-------The printed one is empty
Oh, if it is packaged in the project, the printed Promise { <pending> }
How to return an array, or do I need to use frameworks like mongose?
I use mongoose, which is pretty easy to use. Here are a few demos I wrote https://github.com/treeandgra...
https://github.com/treeandgra...
First of all, I want to state that this problem has nothing to do with the framework or library, it is entirely a promise problem.
1. It’s not that the data is lost, but that your cc variable is defined blindly and is not necessary at all.
2. It can be seen that the author does not know enough about promises. What await returns is the promise object. You can get the data by calling it in a chain.