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