TypeError: Cannot read properties of undefined (reading ‘Link’)

I am working on a piece of code on Nextjs that create a unique id if a user has their profile info in their browser localstorage and redirect them to a link. I have been getting this error message for a while now and i have tried everything, i even asked chatgpt but got nothing. Can anyone help me out?

This is the page.tsx code from create-profile folder:

"use client";

import Setup from "@/components/Setup";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import createUniqueLinkId from "@/libs/createlink";

const Page = () => {
  const router = useRouter();

  interface Profile {
    userName: string;
    avatar: number;
  }

  useEffect(() => {
    const profileFromLocalStorage = localStorage.getItem("profile");
    const profile: Profile | null = profileFromLocalStorage
      ? (JSON.parse(profileFromLocalStorage) as Profile)
      : null;

    const redirectOrSetup = async () => {
      if (profile) {
        try {
          const chatRoomLink = await createUniqueLinkId();
          router.push(`/chatroom/${chatRoomLink}`);
        } catch (error) {
          console.error("Failed to create chat room link", error);
        }
      }
    };

    redirectOrSetup();
  }, []);


  return (
    <div className="lg:mt-32 mt-8">
      <Setup />
    </div>
  );
};

export default Page;

Here is the createlink.ts code:

import { v4 as uuidv4 } from "uuid";
import Link from "@/model/link";
import mongoose from "mongoose";
import { connectToDB } from "@/utils/database"; 

export const createUniqueLinkId = async (): Promise<string> => {
  let linkId = "";
  let isUnique = false;

  try {
    await connectToDB();
    console.log(Link)

    while (!isUnique) {
      linkId = uuidv4();
      
      const existingLink = await Link.findOne({ linkId });

      if (!existingLink) {
        isUnique = true;
      }
    }

    const newLink = new Link({ linkId });
    await newLink.save();

    return linkId;
  } catch (error) {
    console.error("Error creating unique link ID:", error);
    throw new Error("Failed to create a unique link ID");
  }
};

export default createUniqueLinkId;

And finally , here is the link model code:

import mongoose, { Document, Model, Schema } from 'mongoose';

export interface ILink extends Document {
  linkId: string,
  participants: string[];
  createdAt: Date;
}

const linkSchema = new Schema<ILink>({
  linkId:{
    type: String,
    required: true,
    unique: true,
  },
  participants: {
    type: [String],
    default: [],
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
}, { timestamps: true });

const Link: Model<ILink> = mongoose.models.Link || mongoose.model<ILink>('Link', linkSchema);

export default Link;

I would really love to hear from everyone.

I tried to adjust the mongodb connection code, although when i send other api requests, it works perfectly but im confused now, here is the code, if it might help:

"use server"
import mongoose from "mongoose";

let isConnected: boolean = false;

// Connect to MongoDB
export const connectToDB = async (): Promise<void> => {
     
    if (isConnected) {
        console.log('MongoDB is already connected');
        return;  
    }

    try {
        await mongoose.connect(process.env.MONGODB_URI as string, {
            dbName: "anonymous_project"
        });

        isConnected = true;
        console.log('MongoDB connection is successful');
    } catch (error) {
        if (error instanceof Error) {
            throw new Error(`MongoDB connection failed: ${error.message}`);
        } else {
            throw new Error('MongoDB connection failed with an unknown error');
        }
    }
};