I am in the process of creating a service layer on top of mongoDB. I have a User
object that contains an array of referenced Achievements
.
Once the user is authenticated using JWT or another method, I go into the service layer and retrieve the relationship in the following way.
findForUser(userId: string | Types.ObjectId): Promise<Achievement[]> {
return new Promise((resolve) => {
UserSchema.findOne({ _id: userId },
async (err: any, user: User) => {
const AchievementMap: Achievement[] = [];
if (err) throw new Error(err);
user.achievements?.forEach((a) => {
// @ts-ignore
AchievementMap.push(a);
});
resolve(AchievementMap);
});
});
}
How can I implement the async/await approach to handle the callback function passed to UserSchema.findOne
?