Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prisma Mongo Panic called Option::unwrap() on a None value #8598

Closed
CryogenicPlanet opened this issue Aug 5, 2021 · 6 comments
Closed

Prisma Mongo Panic called Option::unwrap() on a None value #8598

CryogenicPlanet opened this issue Aug 5, 2021 · 6 comments
Assignees
Labels
bug/0-unknown Bug is new, does not have information for reproduction or reproduction could not be confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: fluent api topic: mongodb
Milestone

Comments

@CryogenicPlanet
Copy link

CryogenicPlanet commented Aug 5, 2021

Hey I am unable to get this query to work and would love some help

// NOT WORKING
 const invitedProjects = await prisma.user
          .findUnique({ where: { id: userId } })
          .invitedProjects()

Whereas the below query works fine

// WORKING
 const myProjects = await prisma.user
          .findUnique({
            where: { id: userId }
          })
          .myProjects()

I have tried doing something like and this give another error

    const invitedProjects = await prisma.project.findMany({
          where: { collaborators: { some: { id: userId } } }
        })
        
    // ERROR
    ConnectorError(ConnectorError { user_facing_error: None, kind: RawError { code: "unknown", message: "Command failed (Location40081): $in requires an array as a second argument, found: objectId)" } })

EDIT

This causes an error when using prisma studio to view either the Users or Projects models
So it is definitely a problem with the schema or how it is being read. (I am fairly new to prisma so this schema might be wrong, but I think the compiler should probably throw an error for this)

EDIT 2

We ended up moving to postgres and this schema works fine, so this is a bug with mongo specifically

Schema

// We want to connect to the MongoDB datasource
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongodb"]
}

model Team {
  id            String    @id @default(dbgenerated()) @map("_id") @db.ObjectId
  createdAt     DateTime  @default(now())
  teamName      String?
  type          TeamType  @default(TeamTrial)
  owner         User      @relation(name: "Team Owner", fields: [ownerId], references: [id])
  ownerId       String    @db.ObjectId
  collaborators User[]    @relation(name: "Team Collaborators", references: [id])
  projects      Project[] @relation("Team Projects")
}

model ProjectState {
  id             String  @id @default(dbgenerated()) @map("_id") @db.ObjectId
  project        Project @relation(fields: [projectId], references: [id])
  projectId      String  @db.ObjectId
  encodedUpdates Bytes
  clock          BigInt
}

model Project {
  id            String        @id @default(dbgenerated()) @map("_id") @db.ObjectId
  createdAt     DateTime      @default(now())
  projectId     String        @unique @default(uuid()) // This is to use with room id and such
  projectName   String
  owner         User          @relation(name: "Project Owner", fields: [ownerId], references: [id])
  team          Team?         @relation(name: "Team Projects", fields: [teamId], references: [id])
  teamId        String        @db.ObjectId
  ownerId       String        @db.ObjectId
  collaborators User[]        @relation(name: "Project Collaborators", references: [id])
  thumbnail     String?
  dimensions    Int[]
  frameRate     Int
  fileSize      Int[]
  duration      Int?
  state         ProjectState[]
}

model User {
  id              String    @id @default(dbgenerated()) @map("_id") @db.ObjectId
  createdAt       DateTime  @default(now())
  email           String    @unique
  name            String?
  type            UserType  @default(Free)
  myProjects      Project[] @relation("Project Owner")
  invitedProjects Project[] @relation("Project Collaborators")
  myTeams         Team[]    @relation("Team Owner")
  invitedTeams    Team[]    @relation("Team Collaborators")
}

enum UserType {
  Free
  PersonalPro
}

enum TeamType {
  TeamTrial
  TeamPro
  TeamEnterprise
}

Versions

Name Version
Node v14.17.0
OS debian-openssl-1.1.x
Prisma Client 2.28.0
Query Engine query-engine 89facabd0366f63911d089156a7a70125bfbcd27
Database mongo

Query

query {
  findUniqueUser(where: {
    id: "X"
  }) {
    invitedTeams {
      id
      createdAt
      teamName
      type
      ownerId
    }
  }
}

Logs

lient/query-engine-debian-openssl-1.1.x are fine  
  plusX Execution permissions of /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client/query-engine-debian-openssl-1.1.x are fine  
  prisma:engine { cwd: '/mnt/d/Documents/modfy/editor/prisma' }  +2s
  prisma:engine Search for Query Engine in /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client  
  plusX Execution permissions of /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client/query-engine-debian-openssl-1.1.x are fine  +2s
  prisma:engine { flags: [ '--enable-raw-queries', '--port', '38227' ] }  
  prisma:engine stdout  Started http server on http://127.0.0.1:38227  
  prisma:engine Search for Query Engine in /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client  
  plusX Execution permissions of /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client/query-engine-debian-openssl-1.1.x are fine  
  prisma:engine Client Version: 2.28.0  
  prisma:engine Engine Version: query-engine 89facabd0366f63911d089156a7a70125bfbcd27  
  prisma:engine Active provider: mongodb  
  prisma:engine stdout  PANIC in query-engine/connectors/mongodb-query-connector/src/root_queries/read.rs:106:74
called `Option::unwrap()` on a `None` value  
  prisma:engine {
  prisma:engine   error: SocketError: other side closed
  prisma:engine       at Socket.onSocketEnd (/mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/@prisma/client/runtime/index.js:26686:24)
  prisma:engine       at Socket.emit (events.js:388:22)
  prisma:engine       at endReadableNT (internal/streams/readable.js:1336:12)
  prisma:engine       at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  prisma:engine     code: 'UND_ERR_SOCKET'
  prisma:engine   }
  prisma:engine }  
  prisma:engine {
  prisma:engine   error: Error: connect ECONNREFUSED 127.0.0.1:38227
  prisma:engine       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  prisma:engine     errno: -111,
  prisma:engine     code: 'ECONNREFUSED',
  prisma:engine     syscall: 'connect',
  prisma:engine     address: '127.0.0.1',
  prisma:engine     port: 38227
  prisma:engine   }
  prisma:engine }  
  prisma:engine { cwd: '/mnt/d/Documents/modfy/editor/prisma' }  
  prisma:engine Search for Query Engine in /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client  
  plusX Execution permissions of /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client/query-engine-debian-openssl-1.1.x are fine  
  prisma:engine { flags: [ '--enable-raw-queries', '--port', '37355' ] }  
  prisma:engine stdout  Started http server on http://127.0.0.1:37355  
  prisma:engine Search for Query Engine in /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client  
  plusX Execution permissions of /mnt/d/Documents/modfy/editor/node_modules/.pnpm/@prisma+client@2.28.0_prisma@2.28.0/node_modules/.prisma/client/query-engine-debian-openssl-1.1.x are fine  
  prisma:engine Client Version: 2.28.0  
  prisma:engine Engine Version: query-engine 89facabd0366f63911d089156a7a70125bfbcd27  
  prisma:engine Active provider: mongodb  
  prisma:engine stdout  PANIC in query-engine/connectors/mongodb-query-connector/src/root_queries/read.rs:106:74
called `Option::unwrap()` on a `None` value  
  prisma:engine {
  prisma:engine   error: SocketError: other side closed
  prisma:engine       at Sock
@pantharshit00 pantharshit00 added bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. kind/bug A reported bug. team/client Issue for team Client. labels Sep 13, 2021
@ezeikel
Copy link

ezeikel commented Feb 6, 2022

Having a similar issue when trying to run this query:

const clusters = await prisma.cluster.findMany({
  where: {
    followers: { some: { id: userId } },
  },
});

I get this error:
ConnectorError(ConnectorError { user_facing_error: None, kind: RawDatabaseError { code: "unknown", message: "Command failed (Location40081): $in requires an array as a second argument, found: objectId)" } })

The two related models look like this:

model Cluster {
  id          String   @id @default(dbgenerated()) @map("_id") @db.ObjectId
  name        String
  description String?
  sparks      Spark[]  @relation(fields: [sparkIDs])
  sparkIDs    String[] @db.Array(ObjectId)
  user        User     @relation("ClusterOwner", fields: [ownerID], references: [id])
  ownerID     String   @db.ObjectId
  shared      Boolean  @default(false)
  deleted     Boolean  @default(false)
  followers   User[]   @relation("ClusterFollowers", fields: [followerIDs])
  followerIDs String[] @db.Array(ObjectId)
  legacyId    String?  @unique
  meta        Meta[]   @relation(fields: [metaIDs])
  metaIDs     String[] @db.Array(ObjectId)
  log         Log[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([ownerID, id])
  @@map("clusters")
}

model User {
  id               String         @id @default(dbgenerated()) @map("_id") @db.ObjectId
  firstName        String?
  lastName         String?
  name             String?
  email            String         @unique // TODO: doesnt seem to be being enforced
  type             UserType       @default(EXTERNAL_SEA_USER)
  pin              String         @default("0000")
  role             UserRole       @default(USER)
  deleted          Boolean        @default(false)
  legacyId         String?        @unique
  clusterFollowers Cluster[]      @relation("ClusterFollowers")
  clusterOwner     Cluster[]      @relation("ClusterOwner")
  processedForUser Log[]          @relation("ProcessedForUser")
  processedByUser  Log[]          @relation("ProcessedByUser")
  sparks           Spark[]
  subscriptions    Subscription[]
  createdAt        DateTime       @default(now())
  updatedAt        DateTime       @updatedAt

  @@map("users")
}

Any ideas on what might be wrong or is this definitely a bug?

@ezeikel
Copy link

ezeikel commented Feb 7, 2022

Weirdly this does work:

const clusters = await prisma.cluster.findMany({
  where: {
    followerIDs: {
      has: userId,
    },
  },
});

This fixes the issue that was blocking me but I'm still wondering why I can't just use some with followers instead? 🤔

@matthewmueller
Copy link
Contributor

matthewmueller commented Mar 2, 2022

Hey there, I wasn't able to reproduce this error on 3.11.0. Do you mind trying again on the latest version?

Given the following schema:

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

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongodb"]
}

model Cluster {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  name        String
  followers   User[]   @relation("ClusterFollowers", fields: [followerIDs], references: [id])
  followerIDs String[] @db.ObjectId
}

model User {
  id                 String    @id @default(auto()) @map("_id") @db.ObjectId
  name               String
  clusterFollowers   Cluster[] @relation("ClusterFollowers", fields: [clusterFollowerIds], references: [id])
  clusterFollowerIds String[]  @db.ObjectId
}

And the following script:

import { PrismaClient, Prisma } from "@prisma/client"
const prisma = new PrismaClient()

async function main() {
  await prisma.$connect()
  await prisma.user.deleteMany()
  await prisma.cluster.deleteMany()
  const u1 = await prisma.user.create({
    data: {
      name: "Bob",
    },
  })
  const u2 = await prisma.user.create({
    data: {
      name: "Alice",
    },
  })
  const c1 = await prisma.cluster.create({
    data: {
      name: "Tennis",
      followers: {
        connect: [
          {
            id: u1.id,
          },
          {
            id: u2.id,
          },
        ],
      },
    },
  })
  const c2 = await prisma.cluster.create({
    data: {
      name: "Soccer",
      followers: {
        connect: {
          id: u2.id,
        },
      },
    },
  })
  const c3 = await prisma.cluster.create({
    data: {
      name: "Basketball",
      followers: {
        connect: {
          id: u1.id,
        },
      },
    },
  })
  const clusters = await prisma.cluster.findMany({
    where: {
      followers: { some: { id: u1.id } },
    },
  })
  console.log(clusters)
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect())

Running this, you get:

$ ts-node index.ts
[
  {
    id: '621ff2227ee6d06d1682f0c0',
    name: 'Tennis',
    followerIDs: [ '621ff2227ee6d06d1682f0be', '621ff2227ee6d06d1682f0bf' ]
  },
  {
    id: '621ff2237ee6d06d1682f0c2',
    name: 'Basketball',
    followerIDs: [ '621ff2227ee6d06d1682f0be' ]
  }
]

Version

$ npx prisma version
npx prisma version
Environment variables loaded from .env
prisma                  : 3.11.0-dev.30
@prisma/client          : 3.11.0-dev.30
Current platform        : darwin
Query Engine (Node-API) : libquery-engine 4cac12afbeef2fa3eedf1cb87c79bc15e2648836 (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine        : migration-engine-cli 4cac12afbeef2fa3eedf1cb87c79bc15e2648836 (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine    : introspection-core 4cac12afbeef2fa3eedf1cb87c79bc15e2648836 (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary           : prisma-fmt 4cac12afbeef2fa3eedf1cb87c79bc15e2648836 (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash    : 4cac12afbeef2fa3eedf1cb87c79bc15e2648836
Studio                  : 0.458.0
Preview Features        : mongoDb

@pantharshit00 pantharshit00 added bug/0-unknown Bug is new, does not have information for reproduction or reproduction could not be confirmed. and removed bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. labels Mar 4, 2022
@janpio
Copy link
Member

janpio commented Mar 11, 2022

Ping @CryogenicPlanet @ezeikel

@matthewmueller
Copy link
Contributor

Closing, but happy to re-open if this pops back up.

@ezeikel
Copy link

ezeikel commented Mar 15, 2022

@janpio @matthewmueller The issue I was having turned out to be on my side - when calling set on cluster.followers I was just passing an array of IDs and not [{ id: 'id'}, ...] which then messed up the relation when trying to filter on it

So all good from me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug/0-unknown Bug is new, does not have information for reproduction or reproduction could not be confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: fluent api topic: mongodb
Projects
None yet
Development

No branches or pull requests

5 participants