Trying to get data from the Mongodb bank

Asked

Viewed 106 times

1

Guys I want to create a function that returns an array of my database collection, but I need to do this using mongoDB native drive, without Mongoose, I would like some tips. I already have a code, but it doesn’t work:

async function findAll(){
    let users = []
    connectDB().then( db => {
        db.collection('user').find().toArray()
            .then(
                usersDB => users = usersDB
            )
    })
    return users
}

connectDB function:

async function connectDB() {
    const client = await MongoClient.connect(url, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    console.log('conectado!')
    return client.db(db_name)
}

module.exports = { connectDB }

1 answer

2


Although you are declaring the function asynchronous (using the reserved word, or keyword, async), you are not using the functionality that this type of function offers to wait for the result to be obtained, before you can return to the list of users:

async function findAll(){
    let users = []
    // isso é, praticamente, ignorado
    connectDB().then( db => {
        db.collection('user').find().toArray()
            .then(
                usersDB => users = usersDB
            )
    })
    // automaticamente retorna a lista vazia
    return users
}

One wonders: why that passage is ignored? Simply because "it was not asked to wait for the result". And how do you "ask for it to wait"? Through the use of commando await. So even if those callbacks were executed, they would not have the expected effect, since they would no longer be expected.

How to solve? Simple:

async function findAll(){
    let db = await connectDB()
    let users = await db.collection('user').find().toArray()
    return users
}

So he’ll wait for you to return the connection to the database, and then he’ll wait for you to return the list of documents, and then he’ll return the list. And remembering that where this function (or method) is used, one should make the use, or async/await again, or the way you were trying to do with .then().

OBS.: also remembering that this is all part of the subject of Promises!

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.