Prisma link excluding Property A

In my quest, I aim to retrieve all TutelageClasses where the user is not yet registered for the upcoming session. However, the current solution showcases all TutelageClasses regardless of registration status.

My attempt involves executing the following query using Prisma:

SELECT a.id, a.title
FROM a
INNER JOIN ON a.nextSession = b.id
INNER JOIN ON b.id = c.tutelageSession
INNER JOIN ON c.user = d.id
WHERE d.name NOT 'VALUE';

Here are my tables: | a (TutelageClass) | b (TutelageSession) | c | d (User) | | :-: | :-: | :-: | :-: | | id | id | #user | id | | title | title | #tutelageSession | name | | #nextSession |

The simplified version of my Prisma schema looks like this:

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

model TutelageClass {
  id                   String  @id @default(auto()) @map("_id") @db.ObjectId
  title                String

  nextSessionId String? @db.ObjectId
  nextSession TutelageSession?
}

model TutelageSession {
  id         String   @id @default(auto()) @map("_id") @db.ObjectId

  registeredStudentsIDs String[] @db.ObjectId
  tutelageClassId       String   @unique @db.ObjectId

  tutelageClass      TutelageClass @relation(fields: [tutelageClassId], references: [id], onUpdate: Cascade, onDelete: Restrict)
  registeredStudents User[]        @relation("RegisteredStudentsToTutelageSession", fields: [registeredStudentsIDs], references: [id])
}

model User {
  id            String    @id @default(auto()) @map("_id") @db.ObjectId
  name          String?

  registeredToTutelageSessionIDs String[] @db.ObjectId

  registeredToTutelageSession TutelageSession[] @relation("RegisteredStudentsToTutelageSession", fields: [registeredToTutelageSessionIDs], references: [id])
}

Lastly, the code snippet I am experimenting with:

const c = await client.tutelageClass.findMany({
    select: {
        id: true,
        title: true,
    }, where: {
        nextSession: {
            registeredStudents: {
                none: {
                    id: userIdNotRegistered
                }
            }
        }
    }
});

Answer №1

After experimenting with your schema file, I crafted a scenario involving two users, each registered for different sessions of classes. Alice is enrolled in Math Class while Bob is taking Science class. The query to find classes that Alice is not registered for yielded the expected result – Science class.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: ['query'],
});

async function main() {
  const mongoUserId1 = '5f9b9b9b9b9b9b9b9b9b9b9b';

  await prisma.user.create({
    data: {
      id: mongoUserId1,
      name: 'Alice',
      registeredToTutelageSession: {
        create: {
          id: '5f9a9a9a9a9a9a9a9a9a9a9a',
          tutelageClass: {
            create: {
              title: 'Math',
            },
          },
        },
      },
    },
  });

  const mongoUserId2 = '5f9c9c9c9c9c9c9c9c9c9c9c';

  await prisma.user.create({
    data: {
      id: mongoUserId2,
      name: 'Bob',
      registeredToTutelageSession: {
        create: {
          id: '5f9d9d9d9d9d9d9d9d9d9d9d',
          tutelageClass: {
            create: {
              title: 'Science',
            },
          },
        },
      },
    },
  });

  const classes2 = await prisma.tutelageClass.findMany({
    where: {
      nextSession: {
        registeredStudents: {
          none: {
            id: mongoUserId1,
          },
        },
      },
    },
  });

  console.log('classes2', classes2);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Here’s what was generated: https://i.sstatic.net/FdBbj.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to retrieve selected value from Flowbite-React Datepicker due to malfunctioning props change event

I am encountering an issue with extracting the selected value from the Datepicker component in the flowbite-react library while using it with NextJS. The component is being displayed correctly. I attempted the code below, but it does not return anyth ...

The file parameter in the upload is consistently undefined in tsoa-swagger

Having trouble with Tsoa nodejs File upload Followed the tsoa documentation for writing the method, but the output variable is consistently undefined This is my current method https://i.sstatic.net/YrNc0.png @Post('/uploadNewExporterTemplate&apos ...

Utilizing Mongock for a single database within a multi-database environment in a Spring project

I am currently working on a large, legacy multi-module Java Spring Boot project that is connected to one MySql database and two Mongo databases (referred to as codebook and report). My goal is to set up Mongock for performing MongoDB migrations specifi ...

Using Typescript to extract the type from within the function type parameters

I am currently utilizing an imported type definition that contains a function type definition with a fairly complex parameter type: export interface SomeTypeDefinition { someFunction: ( param1: string, param2: { key1: number, key2: s ...

Using JSDoc with TypeScript's generic types: A guide

Can you provide some guidance on the best way to use JSDoc for generic TypeScript functions? I attempted to implement it as shown below, but received a prompt suggesting that JSDoc types may be moved to TypeScript types.ts(80004). When I clicked on the "q ...

What is the reason behind the occurrence of `(User & { _id: Schema.Types.ObjectId; }) | null` when calling findById?

Today marks my debut using typescript and mongoose. Here's a glimpse of what I've worked on. Type export interface User extends Document { _id: ObjectId; lastName: string; } Schema const userSchema = new Schema<User>({ lastName: { t ...

"Unlocking the Safe Option in Mongojs: A Step-by-Step

Take a look at this Node.js code snippet: db = require('mongojs')('database', ['users, sessions']); db.users.insert( { 'email': email, 'password': password, 'firstname': firstname, ' ...

JS for accessing Meteor templates through the DOM

This is a meteor template I created: {{#each p}} <div class="cpl"> <div class="chat-post"> <li class="post"> <div class="nm" id={{_id}}> <a>{{username}}</a> </div> < ...

What is the best way to extract data from multiple FormControl instances using RxJS in Angular?

I am currently subscribed to three FormControl instances named filter1, filter2, and filter3. My goal is to fetch the values of all three whenever any one of them changes. I initially attempted to achieve this using combineLatest, but found that it only em ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Interrogate MongoDB using a regular expression query against an ObjectId

Can a query be executed like the following? db.artigo.find( { _id : ObjectId('520a504a3004bc615fcfcf16') } ) but utilizing a regex on ObjectId? For instance, to retrieve _ids that contain "004" in that position. Note: The objective is to deve ...

Unable to locate PersistentEntity for the specified class java.lang.Void while executing the DeleteAllBy... query in Reactive Mongo

I am currently working on a Spring Boot webflux application that utilizes MongoDB as its backend. My goal is to remove all documents that meet a specific query criteria, so I have implemented a method. fun deleteAllByInsertTimestampIsBefore(to: LocalDateT ...

When using TypeScript, the ReactDOM.render function may not accept certain components

Summary In my TypeScript and React project, I have created the AppContainer.tsx component and exported it as default. In the file app.ts, where I am using ReactDOM to render it on the targeted dom element, I encounter some errors (refer to the image). For ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Customize the nssize for MongoDB version 2.6 to resolve namespace challenges when dealing with a high volume of collections

Recently, while using MongoDB version 2.6, I encountered an issue where mongo ran out of namespace size when the number of collections suddenly increased due to a burst of data. Upon further research, I found that the default nssize is 16 MB, which equate ...

When incorporating MongoDBAdapter into the next-auth file in Next.js, an issue arises when trying to log in with Google

While attempting to follow a tutorial on creating an ecommerce app with NextJS, next-auth, and MongoDB on YouTube, I encountered an error. I came across a Medium article that discussed integrating next-auth and MongoDB into a NextJS app, and the code was a ...

Tips on how to retrieve a stubbed Observable<void> in RxJS

Currently, I am attempting to stub an API and would like to retrieve a stubbed response from my Service. The method in my service appears as follows: public addItem(item): Observable<void> { this.listOfItems.push(item); return of(); } As f ...

Troubleshooting problem with accessing Mongoid

I am currently developing an application with a database embedded in it. The database I am using is MongoId, containing only one entry which stores a token. api.rb def get_wink_token retrieve_token.present? ? retrieve_token : new_token end ...