I have a problem with my code. Any solution that I found are unclear to me.. I want to get a value by returning it by fethcing my database but obviously I don't handle my callback well.
Here is my code :
nbr_users = (key) => {
db.User.find({
shop: key
}, (err, users) => {
if (err) res.json(err)
else
return users.length //it's the value I want
})
}
module.exports = (req, res) => {
db.Account.find({}, (err, accounts) => {
if (err) res.json(err)
else {
var accountMap = {}
var i = 0;
accounts.forEach((account) => {
accountMap[i++] = {
users: nbr_users(account.key) //here I call my function
}
});
res.json({user_list: accountMap})
}
})
}
EDIT: I don't know how to use async/await I try this, I have no idea about how to fix it
function getUsers(key) {
return new Promise(function(resolve, reject) {
db.User.find({
shop: key
}, (err, users) => {
if (err) res.json(err)
else
resolve(users.length)
})
})
}
nbr_users = (key) => {
return await getUsers(key)
}
module.exports = (req, res) => {
db.Account.find({},
(err, accounts) => {
if (err) res.json(err)
else {
var accountMap = {}
var i = 0;
accounts.forEach((account) => {
accountMap[i++] = {
users: nbr_users(account.key)
}
});
res.json({user_list: accountMap})
}
})
}