result.forEach
geeft een reeks beloften terug. Je moet alles tegelijk beloven met Promise.all([])
exports.get_users = (req, res) => {
SubscriptionPlan.find().then(async (result) => {
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
let modifiedData = [];
await Promise.all(
result.map(async(data) => {
if (data.processStatus === "active") {
const response = await Users.findById(data.userId);
modifiedData.push(response);
}
})
);
return res.json(modifiedData);
}).catch((err) => console.log(err));
};
Of kan meteen vinden
exports.get_users = async (req, res) => {
try {
const result = await SubscriptionPlan.find({ processStatus: "active" });
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
const ids = result.map(({ userId }) => userId);
const response = await Users.find({ userId: { $in: ids } });
return res.json(response);
} catch (err) {
console.log(err)
return res.status(400).json({ message: "unable to process" });
}
};