I want to, first of all, fetch the data of a user, then in that user’s history object, I wanna fetch the data of each user there. the problem is, I want to kind of add the amount from the history object together with the user’s data fetched as an object or array, but I get an empty object.
import users from "@/models/users";
import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import dbConnect from "@/util/mongodb";
export async function GET(req, { params }) {
await dbConnect();
try {
const data = await users.findOne({ username: params.id }, { pin: 0 });
const history = await Promise.all(
data.history.map((user) => {
const us = users.findOne(
{ _id: user.id },
{ firstname: 1, username: 1, lastname: 1 }
);
return us;
//I get an empty object when i return {user: us, amount: user.amount}
})
);
return NextResponse.json(history, { status: 200 });
} catch (err) {
return NextResponse.json(err, { status: 500 });
}
}
2
Answers
The problem is that
us
is again a promise (which serialises to an empty JSON object), you would need to wait for it:The reason you’re getting an empty object when you try to return
{ user: us, amount: user.amount }
is that theusers.findOne()
method in your code is missing anawait
keyword, causing the function to return a promise instead of the actual user data. To fix this issue, you need to await theusers.findOne()
method to retrieve the user data correctly.Here’s the updated code snippet with the necessary changes:
I added the
async
keyword to thedata.history.map()
callback function, allowing us to useawait
inside it. By addingawait
beforeusers.findOne()
, you ensure that the function waits for the user data to be fetched before continuing to the next iteration.Now, when you return
{ user: us, amount: user.amount }
, it should include the user object fetched fromusers.findOne()
and the correspondingamount
from the history object.