Here are the refactored versions of your getAllPayins and getPayinById functions with userId populated (i.e., the associated user document is fetched and included in the response). I've also added some minor improvements for better error handling and code readability.
getAllPayins (with userId populated)
export const getAllPayins = async (req, res) => {
try {
const { _id: userId, role } = req.user;
const { page = 1, limit = 10 } = req.query;
const currentPage = parseInt(page, 10);
const perPage = parseInt(limit, 10);
if (currentPage <= 0 || perPage <= 0) {
return res.status(400).json({
success: false,
message: "Invalid pagination parameters. Page and limit must be greater than zero.",
});
}
const skip = (currentPage - 1) * perPage;
let filters = role === "admin" ? { deleted: false } : { userId, deleted: false };
const [payins, totalCount] = await Promise.all([
PayinModel.find(filters)
.skip(skip)
.limit(perPage)
.sort({ createdAt: -1 })
.populate('userId', 'name email profilePicture'), // Populate userId with name, email, and profilePicture
PayinModel.countDocuments(filters),
]);
const totalPages = Math.ceil(totalCount / perPage);
return res.status(200).json({
success: true,
message: payins.length === 0 ? "No Payins found." : "Payins fetched successfully.",
pagination: {
currentPage,
totalPages,
perPageItems: perPage,
totalItems: totalCount,
},
data: payins,
});
} catch (error) {
console.error(`GET PAYIN ERROR: ${error.message}`);
return res.status(500).json({
success: false,
message: `Server error while fetching payins: ${error.message}`,
});
}
};
getPayinById (with userId populated)
export const getPayinById = async (req, res) => {
try {
const { role, _id: userId } = req.user;
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: "Payin ID is required.",
});
}
let filter;
if (role === 'admin') {
filter = { _id: id, deleted: false };
} else {
filter = { _id: id, userId, deleted: false };
}
const payin = await PayinModel.findOne(filter)
.populate('userId', 'name email profilePicture'); // Populate userId with name, email, and profilePicture
if (!payin) {
return res.status(404).json({
success: false,
message: role === 'admin' ? "Payin not found." : "Payin not found or access denied.",
});
}
return res.status(200).json({
success: true,
message: "Payin fetched successfully.",
data: payin,
});
} catch (error) {
console.error(`GET PAYIN BY ID ERROR: ${error.message}`);
return res.status(500).json({
success: false,
message: `Server error while fetching payin: ${error.message}`,
});
}
};