Hello I am having the following problem with my API.
I am calling a function in my models from my service like so,
async getAccounts(/*offset = 0, limit = 500,*/ res) {
try {
let offset = 0;
let limit = 500;
let result = await this.model.getAllAccounts(offset, limit);
console.log(result, "Debugger 3");
return res.status(200).json(result);
} catch (error) {
logger.error('AccountsService::getAccounts', 39);
logger.error(error);
return errorHandler(error, res);
}
}
And the function in my models class looks something like this.
async getAllAccounts(offset, limit) {
// Need to add offset and limit parameters //done
console.log("URL",url);
MongoClient.connect(url, function(err, db) {
if (err) throw err;
logger.log('Query Accounts');
const dbo = db.db("DB_NAME");
dbo.collection('accounts').find({}).skip(offset).limit(limit).toArray(function(err, result) {
if (err) throw err;
db.close();
logger.log("Debugger 2xxx: ",result);
return result;
});
});
}
The problem I am having is that before Debugger 3's output comes before Debugger 2's output.
I think I need to await the result being returned from MongoDB but not sure how to do it. Could anyone please guide me?