How to return mongodb data from a call
迷茫
迷茫 2017-06-26 10:49:30
0
2
1218
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?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
刘奇

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.

const connect = async () => {
    const db = await monguaDb()
    const collection = db.collection('user')
    let b = await collection.find({}).toArray()
    console.log("111---" , b);
    return b; //返回的b是promise对象
}

connect().then((doc) => { //取出b完成后resolve的数据
    console.log(222---" , doc);
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template