0

I have a list of users I would like to look up in my MongoDB database and once I look them up, I want to store them in an array so I can do things with the data. I'm using the official mongodb package in NodeJS. Here's the code

var chatsData = []
for (let userID of chatIDs) {
    db.collection('users').find({ '_id': ObjectId(userID) }).toArray((err, result) => {
        if (err) throw err
            chatsData.push(result)
            console.log(result)
        })
    }
}

console.log('vvv Final data in array: vvv')
console.log(chatsData)

When I run the code this, I get this vvv

vvv Final data in array: vvv
[]
[
  {
    _id: 5eae4c90ad1dd6304c69a75a,
    usnm: 'gohjunhao',
    eml: '[email protected]',
    phnm: '00000000',
    pswd: '$2a$10$IUaxiweNrUUwxZP6XEQfFeTTnbta13/kv6DdebwJ0WT/bM.3fc5ay',
    register_date: 2020-05-03T04:46:08.054Z,
    __v: 0
  }
]
[
  {
    _id: 5ead401f8059852114bf9867,
    usnm: 'gfox.2020',
    eml: '[email protected]',
    phnm: '11111111',
    pswd: '$2a$10$UYaEraoI4Kj0dI.nt5Hbr.LgDL1TNtDOsz7tcxETJW7HRtmgWo.UK',
    register_date: 2020-05-02T09:40:47.684Z,
    __v: 0
  }
]

How do I get a proper array of data in my array so it can be used later? Is what I'm doing wrong? Do I need to use a .then() statement or an async await?
Here's the full code

MongoClient.connect(url, { useUnifiedTopology: true }).then(async chooseDB => {
    db = chooseDB.db('nodejs')

    // Get a list of all tables
    db.listCollections().toArray((err, result) => {
        /***** YOU DON'T NEED TO UNDERSTAND THIS PART OF THE CODE ******/
        if (err) throw err
        var chatList = []
        var chatIDs = []
        for (let i = 0; i < result.length; i++) {
            const table = result[i]
            if (table.name.indexOf(data) > 1) {
                // add tables with personal id to chatList
                chatList.push(table.name)
                // add id's of other chats to out table
                chatIDs.push(table.name.replace('dm', '').replace('~', '').replace(data, ''))
            }
        }
        /***** IT'S JUST HOW I GET MY CHAT ID'S *****/

        // Get data on users
        var chatsData = []
        for (let userID of chatIDs) {
            try{
                let temp = await db.collection('users').find({ '_id': toMongoObjectId(userID) }).toArray()
                chatsData.push(temp)
            }
            catch(error) {
                console.log(error)
            }
        }

        console.log('vvv Final data in array: vvv')
        console.log(chatsData)

        toClient.userData = chatsData
        toClient.users = chatList
        socket.emit('res_chatList', toClient)

    })
})
2
  • Are you like trying to use the chatsData after this for-loop and it acts like the array is empty? Commented May 3, 2020 at 5:09
  • yes. I want the mongo results to be added to chatsData and use it later Commented May 3, 2020 at 5:11

1 Answer 1

1

This can be solved using async-await, write async to the function of then block-like,

mongoclient.connect().then( async (cli) => { 
    db = cli.db(dbName);
    ...
})

your logic to fetch data will be

    var chatsData = []
    for (let userID of chatIDs) {
        try{
             let temp = await db.collection('users').find({ '_id': ObjectId(userID) }).toArray();
             chatsData.push(temp);
        }
        catch(error) {
            console.log(error);
        }
   }
   console.log(chatsData);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, back then I didn't understand the concept of async/await

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.