0

I have three schemas - User, Community and User:

User:

export const UserSchema = new Schema<IUser>({
  address: { type: String, unique: true },
  name: String
}, { timestamps: true });

const UserModel = model<IUser>("User", UserSchema);

Community:

const CommunitySchema = new Schema<ICommunity>({
  slug: { type: String, unique: true },
  name: String, 
  description: String, 
}, { timestamps: true });

UserCommunity:

export const UserCommunitySchema = new Schema<IUserCommunity>({
  user: { type: Schema.Types.ObjectId, ref: "User" },
  community: { type: Schema.Types.ObjectId, ref: 'Community' },
  joinedAt: Date,
  leavedAt: Date,
  isActive: Boolean,
}, { timestamps: true });

const UserCommunityModel = model<IUserCommunity>("UserCommunity", UserCommunitySchema);

User can be in many communities. I can access userCommunities well with the ref User and Community: userCommunity.user and userCommunity.community, but I couldn't make it work to add a reference to the userCommunity to the User neither Community.

I'd like to be able to do user.userCommunities or community.userCommunities but it didn't work even if I added the reference to both to the UserCommunity. I also tried the virtual property from mongoose.

Could you help me to achieve the goal?)

Petr
  • 1,853
  • 2
  • 25
  • 49

0 Answers0