Issue with finding users not followed by a specific user in Prisma schema

28 views Asked by At

I am trying to retrieve all the users who are not the current logged in user (the current logged in user is specified by userId) and is also not followed by the current logged in user.

This is my database schema,

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

model User {
  id             String   @id @default(auto()) @map("_id") @db.ObjectId
  username       String   @unique
  imageUrl       String
  externalUserId String   @unique
  bio            String?
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt
  follower       Follow[] @relation("following")
  following      Follow[] @relation("follower")
}

model Follow {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  followerId  String   @db.ObjectId
  follower    User     @relation("follower", fields: [followerId], references: [id])
  followingId String   @db.ObjectId
  following   User     @relation("following", fields: [followingId], references: [id])
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([followerId, followingId])
  @@index([followerId])
  @@index([followingId])
}

where follower relation in the User model specifies the list of users who are following a particular user (say A). and following relation in the User model specifies the list of users who a particular user (A) is following.

I am using the below query to achieve the above mentioned purpose

users = await prisma.user.findMany({
  where: {
    AND: [
      {
        NOT: {
          id: userId,
        },
      },
      {
        NOT: {
          follower: {
            some: {
              followerId: userId,
            },
          },
        },
      },
    ],
  },
  orderBy: {
    createdAt: "desc",
  },
});

But this query only returns the users who are being followed by the current user (userId). I have no clue as to why this is happening. Can anyone please help? What is the right way to do this?

0

There are 0 answers