threads
threads copied to clipboard
I created the community but it's not in the database please fix for me
I created the community but it's not in the database please fix for me
same problem for me.
same problem for me. Did you fix this?
Hey, Are You Still Facing any Error ?
If Yes , First Check You Clerk --> Organizations
Check If it is showing the Organization You made , If Its doesn't Showing Then You must have Issue in Your Code .. Please Share You Community Code and Community Action Code , So that I Can Help You
Same problem
Check Your Commnunity Code --> Id and Page.tsx and Community Action Code , or could you please share that
### Community CODE
`import Image from "next/image"; import { currentUser } from "@clerk/nextjs";
import { communityTabs } from "@/constants";
import UserCard from "@/components/cards/UserCard"; import ThreadsTab from "@/components/shared/ThreadsTab"; import ProfileHeader from "@/components/shared/ProfileHeader"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { fetchCommunityDetails } from "@/lib/actions/community.actions";
async function Page({ params }: { params: { id: string } }) { const user = await currentUser(); if (!user) return null;
const communityDetails = await fetchCommunityDetails(params.id);
return (
<div className='mt-9'>
<Tabs defaultValue='threads' className='w-full'>
<TabsList className='tab'>
{communityTabs.map((tab) => (
<TabsTrigger key={tab.label} value={tab.value} className='tab'>
<Image
src={tab.icon}
alt={tab.label}
width={24}
height={24}
className='object-contain'
/>
<p className='max-sm:hidden'>{tab.label}</p>
{tab.label === "Threads" && (
<p className='ml-1 rounded-sm bg-light-4 px-2 py-1 !text-tiny-medium text-light-2'>
{communityDetails.threads.length}
</p>
)}
</TabsTrigger>
))}
</TabsList>
<TabsContent value='threads' className='w-full text-light-1'>
{/* @ts-ignore */}
<ThreadsTab
currentUserId={user.id}
accountId={communityDetails._id}
accountType='Community'
/>
</TabsContent>
<TabsContent value='members' className='mt-9 w-full text-light-1'>
<section className='mt-9 flex flex-col gap-10'>
{communityDetails.members.map((member: any) => (
<UserCard
key={member.id}
id={member.id}
name={member.name}
username={member.username}
imgUrl={member.image}
personType='User'
/>
))}
</section>
</TabsContent>
<TabsContent value='requests' className='w-full text-light-1'>
{/* @ts-ignore */}
<ThreadsTab
currentUserId={user.id}
accountId={communityDetails._id}
accountType='Community'
/>
</TabsContent>
</Tabs>
</div>
</section>
); }
export default Page; `
Community.actions.ts
`"use server";
import { FilterQuery, SortOrder } from "mongoose";
import Community from "../models/community.model"; import Thread from "../models/thread.model"; import User from "../models/user.model";
import { connectToDB } from "../mongoose";
export async function createCommunity( id: string, name: string, username: string, image: string, bio: string, createdById: string // Change the parameter name to reflect it's an id ) { try { connectToDB();
// Find the user with the provided unique id
const user = await User.findOne({ id: createdById });
if (!user) {
throw new Error("User not found"); // Handle the case if the user with the id is not found
}
const newCommunity = new Community({
id,
name,
username,
image,
bio,
createdBy: user._id, // Use the mongoose ID of the user
});
const createdCommunity = await newCommunity.save();
// Update User model
user.communities.push(createdCommunity._id);
await user.save();
return createdCommunity;
} catch (error) { // Handle any errors console.error("Error creating community:", error); throw error; } }
export async function fetchCommunityDetails(id: string) { try { connectToDB();
const communityDetails = await Community.findOne({ id }).populate([
"createdBy",
{
path: "members",
model: User,
select: "name username image _id id",
},
]);
return communityDetails;
} catch (error) { // Handle any errors console.error("Error fetching community details:", error); throw error; } }
export async function fetchCommunityPosts(id: string) { try { connectToDB();
const communityPosts = await Community.findById(id).populate({
path: "threads",
model: Thread,
populate: [
{
path: "author",
model: User,
select: "name image id", // Select the "name" and "_id" fields from the "User" model
},
{
path: "children",
model: Thread,
populate: {
path: "author",
model: User,
select: "image _id", // Select the "name" and "_id" fields from the "User" model
},
},
],
});
return communityPosts;
} catch (error) { // Handle any errors console.error("Error fetching community posts:", error); throw error; } }
export async function fetchCommunities({ searchString = "", pageNumber = 1, pageSize = 20, sortBy = "desc", }: { searchString?: string; pageNumber?: number; pageSize?: number; sortBy?: SortOrder; }) { try { connectToDB();
// Calculate the number of communities to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;
// Create a case-insensitive regular expression for the provided search string.
const regex = new RegExp(searchString, "i");
// Create an initial query object to filter communities.
const query: FilterQuery<typeof Community> = {};
// If the search string is not empty, add the $or operator to match either username or name fields.
if (searchString.trim() !== "") {
query.$or = [
{ username: { $regex: regex } },
{ name: { $regex: regex } },
];
}
// Define the sort options for the fetched communities based on createdAt field and provided sort order.
const sortOptions = { createdAt: sortBy };
// Create a query to fetch the communities based on the search and sort criteria.
const communitiesQuery = Community.find(query)
.sort(sortOptions)
.skip(skipAmount)
.limit(pageSize)
.populate("members");
// Count the total number of communities that match the search criteria (without pagination).
const totalCommunitiesCount = await Community.countDocuments(query);
const communities = await communitiesQuery.exec();
// Check if there are more communities beyond the current page.
const isNext = totalCommunitiesCount > skipAmount + communities.length;
return { communities, isNext };
} catch (error) { console.error("Error fetching communities:", error); throw error; } }
export async function addMemberToCommunity( communityId: string, memberId: string ) { try { connectToDB();
// Find the community by its unique id
const community = await Community.findOne({ id: communityId });
if (!community) {
throw new Error("Community not found");
}
// Find the user by their unique id
const user = await User.findOne({ id: memberId });
if (!user) {
throw new Error("User not found");
}
// Check if the user is already a member of the community
if (community.members.includes(user._id)) {
throw new Error("User is already a member of the community");
}
// Add the user's _id to the members array in the community
community.members.push(user._id);
await community.save();
// Add the community's _id to the communities array in the user
user.communities.push(community._id);
await user.save();
return community;
} catch (error) { // Handle any errors console.error("Error adding member to community:", error); throw error; } }
export async function removeUserFromCommunity( userId: string, communityId: string ) { try { connectToDB();
const userIdObject = await User.findOne({ id: userId }, { _id: 1 });
const communityIdObject = await Community.findOne(
{ id: communityId },
{ _id: 1 }
);
if (!userIdObject) {
throw new Error("User not found");
}
if (!communityIdObject) {
throw new Error("Community not found");
}
// Remove the user's _id from the members array in the community
await Community.updateOne(
{ _id: communityIdObject._id },
{ $pull: { members: userIdObject._id } }
);
// Remove the community's _id from the communities array in the user
await User.updateOne(
{ _id: userIdObject._id },
{ $pull: { communities: communityIdObject._id } }
);
return { success: true };
} catch (error) { // Handle any errors console.error("Error removing user from community:", error); throw error; } }
export async function updateCommunityInfo( communityId: string, name: string, username: string, image: string ) { try { connectToDB();
// Find the community by its _id and update the information
const updatedCommunity = await Community.findOneAndUpdate(
{ id: communityId },
{ name, username, image }
);
if (!updatedCommunity) {
throw new Error("Community not found");
}
return updatedCommunity;
} catch (error) { // Handle any errors console.error("Error updating community information:", error); throw error; } }
export async function deleteCommunity(communityId: string) { try { connectToDB();
// Find the community by its ID and delete it
const deletedCommunity = await Community.findOneAndDelete({
id: communityId,
});
if (!deletedCommunity) {
throw new Error("Community not found");
}
// Delete all threads associated with the community
await Thread.deleteMany({ community: communityId });
// Find all users who are part of the community
const communityUsers = await User.find({ communities: communityId });
// Remove the community from the 'communities' array for each user
const updateUserPromises = communityUsers.map((user) => {
user.communities.pull(communityId);
return user.save();
});
await Promise.all(updateUserPromises);
return deletedCommunity;
} catch (error) { console.error("Error deleting community: ", error); throw error; } } `
I even tried cloning adrian's app but in that also I'm facing the same issue.
Hey ,Kashan Haider , I saw Your Code and I found that In You Community Code in [id]--> page.tsx
You Imported ProfileHeader but you are not using that
I am checking you code and please make sure to use Profile Header
not working
i have Organizations in clerk but it not in mongodb
i have Organizations in clerk but it not in mongodb
Please Re-Check Community Code and MongoDb Schema (Community Schema)
https://github.com/vananh0107/Threads-Clone here is my code please fix for me =(((
https://github.com/vananh0107/Threads-Clone here is my code please fix for me =(((
Okay I am Sharing My Code with You , You can replace it Community Card :- import Image from "next/image"; import Link from "next/link";
import { Button } from "../ui/button";
interface Props { id: string; name: string; username: string; imgUrl: string; bio: string; members: { image: string; }[]; }
function CommunityCard({ id, name, username, imgUrl, bio, members }: Props) {
return (
<article className='community-card'>
<div className='flex flex-wrap items-center gap-3'>
<Link href={/communities/${id}
} className='relative h-12 w-12'>
<Image
src={imgUrl}
alt='community_logo'
fill
className='rounded-full object-cover'
/>
</Link>
<div>
<Link href={`/communities/${id}`}>
<h4 className='text-base-semibold text-light-1'>{name}</h4>
</Link>
<p className='text-small-medium text-gray-1'>@{username}</p>
</div>
</div>
<p className='mt-4 text-subtle-medium text-gray-1'>{bio}</p>
<div className='mt-5 flex flex-wrap items-center justify-between gap-3'>
<Link href={`/communities/${id}`}>
<Button size='sm' className='community-card_btn'>
View
</Button>
</Link>
{members.length > 0 && (
<div className='flex items-center'>
{members.map((member, index) => (
<Image
key={index}
src={member.image}
alt={`user_${index}`}
width={28}
height={28}
className={`${
index !== 0 && "-ml-2"
} rounded-full object-cover`}
/>
))}
{members.length > 3 && (
<p className='ml-1 text-subtle-medium text-gray-1'>
{members.length}+ Users
</p>
)}
</div>
)}
</div>
</article>
); }
export default CommunityCard;
Community Tabs in Constant :- export const communityTabs = [ { value: "threads", label: "Threads", icon: "/assets/reply.svg" }, { value: "members", label: "Members", icon: "/assets/members.svg" }, { value: "requests", label: "Requests", icon: "/assets/request.svg" }, ];
Community Action -> "use server";
import { FilterQuery, SortOrder } from "mongoose";
import Community from "../models/community.model"; import Thread from "../models/thread.model"; import User from "../models/user.model";
import { connectToDB } from "../mongoose";
export async function createCommunity( id: string, name: string, username: string, image: string, bio: string, createdById: string // Change the parameter name to reflect it's an id ) { try { connectToDB();
// Find the user with the provided unique id
const user = await User.findOne({ id: createdById });
if (!user) {
throw new Error("User not found"); // Handle the case if the user with the id is not found
}
const newCommunity = new Community({
id,
name,
username,
image,
bio,
createdBy: user._id, // Use the mongoose ID of the user
});
const createdCommunity = await newCommunity.save();
// Update User model
user.communities.push(createdCommunity._id);
await user.save();
return createdCommunity;
} catch (error) { // Handle any errors console.error("Error creating community:", error); throw error; } }
export async function fetchCommunityDetails(id: string) { try { connectToDB();
const communityDetails = await Community.findOne({ id }).populate([
"createdBy",
{
path: "members",
model: User,
select: "name username image _id id",
},
]);
return communityDetails;
} catch (error) { // Handle any errors console.error("Error fetching community details:", error); throw error; } }
export async function fetchCommunityPosts(id: string) { try { connectToDB();
const communityPosts = await Community.findById(id).populate({
path: "threads",
model: Thread,
populate: [
{
path: "author",
model: User,
select: "name image id", // Select the "name" and "_id" fields from the "User" model
},
{
path: "children",
model: Thread,
populate: {
path: "author",
model: User,
select: "image _id", // Select the "name" and "_id" fields from the "User" model
},
},
],
});
return communityPosts;
} catch (error) { // Handle any errors console.error("Error fetching community posts:", error); throw error; } }
export async function fetchCommunities({ searchString = "", pageNumber = 1, pageSize = 20, sortBy = "desc", }: { searchString?: string; pageNumber?: number; pageSize?: number; sortBy?: SortOrder; }) { try { connectToDB();
// Calculate the number of communities to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;
// Create a case-insensitive regular expression for the provided search string.
const regex = new RegExp(searchString, "i");
// Create an initial query object to filter communities.
const query: FilterQuery<typeof Community> = {};
// If the search string is not empty, add the $or operator to match either username or name fields.
if (searchString.trim() !== "") {
query.$or = [
{ username: { $regex: regex } },
{ name: { $regex: regex } },
];
}
// Define the sort options for the fetched communities based on createdAt field and provided sort order.
const sortOptions = { createdAt: sortBy };
// Create a query to fetch the communities based on the search and sort criteria.
const communitiesQuery = Community.find(query)
.sort(sortOptions)
.skip(skipAmount)
.limit(pageSize)
.populate("members");
// Count the total number of communities that match the search criteria (without pagination).
const totalCommunitiesCount = await Community.countDocuments(query);
const communities = await communitiesQuery.exec();
// Check if there are more communities beyond the current page.
const isNext = totalCommunitiesCount > skipAmount + communities.length;
return { communities, isNext };
} catch (error) { console.error("Error fetching communities:", error); throw error; } }
export async function addMemberToCommunity( communityId: string, memberId: string ) { try { connectToDB();
// Find the community by its unique id
const community = await Community.findOne({ id: communityId });
if (!community) {
throw new Error("Community not found");
}
// Find the user by their unique id
const user = await User.findOne({ id: memberId });
if (!user) {
throw new Error("User not found");
}
// Check if the user is already a member of the community
if (community.members.includes(user._id)) {
throw new Error("User is already a member of the community");
}
// Add the user's _id to the members array in the community
community.members.push(user._id);
await community.save();
// Add the community's _id to the communities array in the user
user.communities.push(community._id);
await user.save();
return community;
} catch (error) { // Handle any errors console.error("Error adding member to community:", error); throw error; } }
export async function removeUserFromCommunity( userId: string, communityId: string ) { try { connectToDB();
const userIdObject = await User.findOne({ id: userId }, { _id: 1 });
const communityIdObject = await Community.findOne(
{ id: communityId },
{ _id: 1 }
);
if (!userIdObject) {
throw new Error("User not found");
}
if (!communityIdObject) {
throw new Error("Community not found");
}
// Remove the user's _id from the members array in the community
await Community.updateOne(
{ _id: communityIdObject._id },
{ $pull: { members: userIdObject._id } }
);
// Remove the community's _id from the communities array in the user
await User.updateOne(
{ _id: userIdObject._id },
{ $pull: { communities: communityIdObject._id } }
);
return { success: true };
} catch (error) { // Handle any errors console.error("Error removing user from community:", error); throw error; } }
export async function updateCommunityInfo( communityId: string, name: string, username: string, image: string ) { try { connectToDB();
// Find the community by its _id and update the information
const updatedCommunity = await Community.findOneAndUpdate(
{ id: communityId },
{ name, username, image }
);
if (!updatedCommunity) {
throw new Error("Community not found");
}
return updatedCommunity;
} catch (error) { // Handle any errors console.error("Error updating community information:", error); throw error; } }
export async function deleteCommunity(communityId: string) { try { connectToDB();
// Find the community by its ID and delete it
const deletedCommunity = await Community.findOneAndDelete({
id: communityId,
});
if (!deletedCommunity) {
throw new Error("Community not found");
}
// Delete all threads associated with the community
await Thread.deleteMany({ community: communityId });
// Find all users who are part of the community
const communityUsers = await User.find({ communities: communityId });
// Remove the community from the 'communities' array for each user
const updateUserPromises = communityUsers.map((user) => {
user.communities.pull(communityId);
return user.save();
});
await Promise.all(updateUserPromises);
return deletedCommunity;
} catch (error) { console.error("Error deleting community: ", error); throw error; } }
Community Model :- import mongoose from "mongoose";
const communitySchema = new mongoose.Schema({ id: { type: String, required: true, }, username: { type: String, unique: true, required: true, }, name: { type: String, required: true, }, image: String, bio: String, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, threads: [ { type: mongoose.Schema.Types.ObjectId, ref: "Thread", }, ], members: [ { type: mongoose.Schema.Types.ObjectId, ref: "User", }, ], });
const Community = mongoose.models.Community || mongoose.model("Community", communitySchema);
export default Community;
If You still Have any Error Feel free to ask and please once check you MongoDb connection .
has anyone found the solution, i cant seem to figure it out
has anyone found the solution, i cant seem to figure it out same for me
Can some one help me out with my code unable to figure out the communities part
Can some one help me out with my code unable to figure out the communities part
Okay, Could you please elaborate, on what type of issue you are facing?
Yes in the Clerk organization i got an error response of something 401
same issue