Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results:
const users = posts.map(async (post) => await prisma.user.findUnique({ where: { id: post.authorId }}));
Dissatisfied with the outcome, I decided to try a more traditional method which proved successful:
const users = []
for (let i = 0; i < posts.length; i++) {
const user = await prisma.user.findUnique({
where: {
id: posts[i].authorId,
},
});
users.push(user);
}
I initially suspected the issue might be related to the arrow syntax or implicit return, so I made adjustments as follows:
const getUsers = async (post: Post) => {
const user = await prisma.user.findUnique({
where: {
id: post.authorId,
},
});
console.log(user);
return user;
};
const users = posts.map(getUsers);
Although the user object was successfully logged to the console, it still did not return the expected value, resulting in an array filled with empty objects matching the size of the posts array. Can anyone identify where I may have gone wrong?
Note that in this scenario, I am utilizing Prisma as an ORM.