Combining Prisma results into a unified object

I am currently working on a project using nextjs 13 and prisma ORM with MongoDB. My task involves fetching roles along with their permissions to create an admin role matrix. Here is the schema for the Role model.

model Role {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  name        String   @unique
  userIDs     String[] @db.ObjectId
  users       User[]   @relation(fields: [userIDs], references: [id])
  permissions String[]

  @@map("roles")
}

When I fetch the records, I want to manipulate them slightly. Below is the query result I get.

const roles = await prisma.role.findMany({
    select: {
        name: true,
        permissions: true,
    }
})
console.log(roles);
 [
  { name: 'User', permissions: [ 'permissions.user.view.dashboard' ] },
  {
    name: 'Admin',
    permissions: [
      'permissions.admin.view.dashboard',
      'permissions.user.view.dashboard'
    ]
  }
]

I aim to combine the role name with each permission into one object as follows:

{
    'User.permissions.user.view.dashboard',
    'Admin.permissions.user.view.dashboard',
    'Admin.permissions.admin.view.dashboard'
}

Can this be achieved directly in prisma? If not, how can it be done in JavaScript?

Answer №1

In order to perform a transformation on this object at the Prisma level, direct manipulation is not possible. However, you can accomplish this transformation by following these steps:

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

const prisma = new PrismaClient();

async function main() {
  const roles = await prisma.role.findMany({
    select: {
      name: true,
      permissions: true,
    },
  });
  console.log(roles);

  const updatedRoles = [];

  roles.forEach((role) => {
    role.permissions.forEach((permission) => {
      updatedRoles.push(`${role.name}.${permission}`);
    });
  });

  console.log(updatedRoles);
}

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

For reference, here is an example response image: https://i.sstatic.net/q8D4g.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

What steps can I take to design a functional hamburger menu?

After multiple attempts to create a hamburger menu, I have hit a roadblock. Clicking on the menu icon transforms it into an 'X', but unfortunately, it does not trigger the opening of the menu. Despite days of effort and research, I have yet to fi ...

MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue? I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents. var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray(); De ...

Next.js - Vercel deployment unsuccessful- An unanticipated internal issue has arisen

Our Next.js project was successfully hosted on Vercel until now. However, after deploying my site with a large number of pregenerated static pages (approximately 7500 localized FAQ pages), issues arose. Below is the Build log: [15:22:56.443] Cloning githu ...

Affixing a navigation bar to the top while scrolling

Does anyone know how to create a navigation bar that will "dock" to the top of the browser when scrolled to, and undock when scrolled back up? Check out my code snippet here: http://jsfiddle.net/gLQtx/ $(function() { var initPos = $('#stickyNav&apo ...

Enhancing Line Graphs in React Recharts: Implementing Filters for Improved Visualization

Within my Next.js application, I am working on integrating the recharts library from . My goal is to add a filter option to the charts for timeframes such as 1 day, 1 week, and 1 month. How can I customize the graph to include this feature? Alternatively, ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

Guide on correctly aligning a Blender animation export with Three.js

After successfully exporting an animation from Blender using the Three.js export utility and adding it to a Three.js scene, I encountered an issue when trying to position it manually. Here is the code snippet I am using for creating the mesh and animation ...

A guide to downloading a file linked to Javascript with the help of Java

I have a unique request here. I am looking for a solution using HttpUrlConnection that can interact with JavaScript directly on a webpage, instead of relying on Selenium as a workaround. Can anyone assist me with this? The webpage contains a link (hidden ...

Enable the generation of scss.d.ts files with Next.js

I'm currently working on a project that requires the generation of .d.ts files for the scss it produces. Instead of manually creating these files, I have integrated css-modules-typescript-loader with Storybook to automate this process. However, I am ...

Using Jquery ajax, I am interested in storing a single value into a variable for future use in JavaScript

I'm finally able to retrieve a JSON Get request, but I'm struggling with utilizing the information effectively. The array contains 9 items, but I only need one specific value - the id. I want to extract this id and save it in a variable for futur ...

There seems to be a hiccup in the distribution build of Angular grunt, as it is unable to locate the

While testing the build, everything runs smoothly. However, when attempting to build the distribution, an error is encountered: An error occurred: Cannot find module '/Users/matt.sich/Documents/angularProjects/firstProject/node_modules/grunt-usemin/l ...

jQuery is successfully manipulating pagination on CodeIgniter, however, the link is being updated as well

I've been working on a HTML page called view_closing.php. It includes a table with pagination, and my aim is to ensure that the table can move to another record without refreshing the entire page, all while remaining at the same address: http://localh ...

Creating a form that utilizes both jQuery and PHP to send the results, now including the complete code for reference

Full code update included. Changing the question: What occurs when all questions are answered in endQuiz, resulting in a user score? A form is displayed for the user to complete and submit to a designated email address. However, upon completing the form a ...

Obtaining worth from an entity

I have a collection of objects structured like so: [Object { image = "images/item-1.png" , heading = "Careers" , text = "Lorem ipsum dolor sit a...ctetur adipiscing elit." }, Object { image = "images/item-2. ...

Having trouble with my code trying to transfer elements back and forth between two unordered lists using an "addEventListener"

I have developed a task management system where users can create a to-do list for their daily tasks. Upon completion of a task, they can tick the checkbox next to it, which will trigger a strikethrough effect. The completed tasks are then moved from the "u ...

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Retrieve data from a different field using an aggregate function

Just beginning my journey in the world of MongoDB. My collection contains the following data: { "_id" : ObjectId("5735d8d4d147aa34e440988f"), "DeviceLogId" : "26962", "DeviceId" : "10", "UserId" : "78", "LogDateTime" : ISODate("2 ...

Creating a universal representation of the global object in JavaScript that is not tied to any specific implementation

Looking to define the global object in JavaScript with just one line of code: var global = this.global || this; This statement is within the global scope, meaning that in browsers, the this keyword refers to the window object. If this is the first line o ...

The issue of incorrect encoding in JavaScript Blob while retrieving a file from the server

Implementing a FileStreamResult from C# in a SPA website (using .NET Core 2, SPA React template), I make a request to fetch a file from my endpoint. This triggers the following response in C#: var file = await _docService.GetFileAsync(token.UserName, inst ...

NodeJS Error: Attempting to access 'json' property from an undefined source

I'm in the process of setting up a CronJob to make an API call and save the response into the database: const CronJob = require("cron").CronJob; const btc_price_ticker = require("../../controllers/BtcExchange/Ticker"); const currency = require("../.. ...