Skip to content

Commit 19087a3

Browse files
author
Wcoder547
committed
subscriber using aggregation pipeline
1 parent 7c8b724 commit 19087a3

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

project-backend/src/controllers/user.controller.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,81 @@ const updateuserAvatar = AsyncHandler(async (req, res) => {
309309
.status(200)
310310
.json(new ApiResponse(200, updatedAvatar, "avatar successfully updated"));
311311
});
312+
313+
const getuserChannelProfile = AsyncHandler(async (req, res) => {
314+
const { username } = req.params;
315+
316+
if (!username) {
317+
throw new ApiError(400, "cannot get username ");
318+
}
319+
320+
const channel = await User.aggregate([
321+
{
322+
$match: {
323+
username: username?.toLowerCase(),
324+
},
325+
},
326+
{
327+
$lookup: {
328+
from: "subScriptions", //schema name
329+
localField: "_id", //subscriber_id
330+
foreignField: "channel", //channel
331+
as: "totalSubscriber", //result
332+
},
333+
},
334+
{
335+
$lookup: {
336+
from: "subScriptions",
337+
localField: "_id",
338+
foreignField: "subscriber",
339+
as: "subscribedTo",
340+
},
341+
},
342+
{
343+
$addFields: {
344+
//addfields use for adding a fields on basis some operations
345+
subscriberCount: {
346+
$size: "$totalSubscriber",
347+
},
348+
subscribedtoCount: {
349+
$size: "$subscribedTo",
350+
},
351+
isSubscriber: {
352+
$cond: {
353+
if: { $in: [req.user?._id, "$totalSubscriber.subscriber"] },
354+
then: true,
355+
else: false,
356+
},
357+
},
358+
},
359+
},
360+
361+
{
362+
$project: {
363+
fullname: 1,
364+
username: 1,
365+
email: 1,
366+
avatar: 1,
367+
coverimage: 1,
368+
subscriberCount: 1,
369+
subscribedtoCount: 1,
370+
isSubscriber: 1,
371+
},
372+
},
373+
]);
374+
375+
console.log(channel);
376+
if (!channel?.length) {
377+
throw new ApiError(400, "user channel does not exisist");
378+
}
379+
380+
return res
381+
.status(200)
382+
.json(
383+
new ApiResponse(200, channel, "user channel data fetch successfully")
384+
);
385+
});
386+
312387
export {
313388
userRegister,
314389
userLogin,
@@ -319,4 +394,5 @@ export {
319394
updateAccountDetails,
320395
updateuserAvatar,
321396
updateuserCovwer,
397+
getuserChannelProfile,
322398
};

0 commit comments

Comments
 (0)