search

Home  >  Q&A  >  body text

How to return mongodb data from a call

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?

迷茫迷茫2733 days ago1244

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-06-26 10:51:30

    I use mongoose, which is pretty easy to use. Here are a few demos I wrote https://github.com/treeandgra...

    https://github.com/treeandgra...

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-26 10:51:30

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

    reply
    0
  • Cancelreply