Search code examples
javascripttypescriptmongodbgraphqlprisma

MongoDB & Prisma: unilateral M-to-N relation


Is there a way to make an unilateral m-to-n relation or must both collections have each other's ids? I'm trying to do something like this:

model Country {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  name            String    @unique
  users           User[]
}

model User {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  userName        String    @unique
  countryIds      String[]  @db.ObjectId
  countries       Country[] @relation(fields: [countryIds], references: [id])
  // ....
}

But prisma is making me add another field to Country to store the users ids... Like this:

model Country {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  name            String    @unique
  userIds         String[]  @db.ObjectId
  users           Player[]  @relation(fields: [userIds], references: [id])
}

I don't need that data and it's not logically needed. Is there any way to bypass that? Any workaround?


Solution

  • After some testing I've found that if I leave that userIds field, even though it does not exist in any document, the user's countries could still be correctly queried. The only drawback(not really) is that I can't query the users from the countries. But I guess it makes sense since if I actually needed to query them, adding the userIds relation to the country would also make sense. The actual problem is the error that doesn't let me build/run the code without userIds even though it works fine without it.

    EDIT:

    My schema ended up like this @Min Somai:

    model Country {
      id              String    @id @default(auto()) @map("_id") @db.ObjectId
      name            String    @unique
      userIds         String[]  @db.ObjectId
      users           User[]    @relation(fields: [countryIds], references: [id])
    }
    
    model User {
      id              String    @id @default(auto()) @map("_id") @db.ObjectId
      userName        String    @unique
      countryIds      String[]  @db.ObjectId
      countries       Country[] @relation(fields: [countryIds], references: [id])
      // ....
    }