I am using mongo to search for all entries with a value that is like whatever is passed into the searchForAsset method. When I use the .toArray method and I console.log(result) the array of files is printed in array format. However when I return that exact same variable below the console.log and I console.log it in the .then() below, it comes back as "result: undefined". Why doesn't the .then() wait for the result to be returned correctly?
async function searchForAsset(nameToQuery){
const client = await mongoConnect()
client.db(process.env.DATABASE_NAME).collection(process.env.ASSET_COLLECTION).find({asset_name: RegExp(nameToQuery)}).toArray(function(err, result) {
if (err) throw err
console.log(result)
client.close()
return result
})
}
searchForAsset("Solution").then(result => {
console.log("result: "+result)
})
Edit: I changed the code to this and it still returns undefined:
async function searchForAsset(nameToQuery){
const client = await mongoConnect()
const result = await client.db(process.env.DATABASE_NAME).collection(process.env.ASSET_COLLECTION).find({asset_name: RegExp(nameToQuery)}).toArray(function(err, result) {
if (err) throw err
console.log(result)
client.close()
})
return result
}
searchForAsset("Solution").then(result => {
console.log("result: "+result)
})
const result = await client.db(process.env.DATABASE_NAME).collection(process.env.ASSET_COLLECTION).find({asset_name: RegExp(nameToQuery)}).toArray()or you need to addreturnbeforeclient.db(...)undefinedconst result = await client.db(process.env.DATABASE_NAME).collection(process.env.ASSET_COLLECTION).find({asset_name: RegExp(nameToQuery)}).toArray(function(err, result) {})and then after that doreturn resultit still results in an undefinedconsole.log()in the.then()awaitgenerally. Try copying code from this gistresult: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]...and so on