What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole.

The issue arises when the UserRole is also retrieved in the query below:

async getUser(conditionals: object) {
  return await this.userRepository.findOne({
    where: { ...conditionals },
    include: [{ model: Role, attributes: 'value' } ]
  });
}

Here's an example of the response (please disregard the format, as the data was encoded and decoded from a jwt):

{
  "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
  "username": "bl4drnnr",
  "roles": [
    {
      "value": "USER",
      "UserRole": {
        "id": "e9d2afe8-ddd1-4311-ab14-6638b79d0d80",
        "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
        "roleId": "123e4567-e89b-12d3-a456-426614174001"
      }
    }
  ],
  "type": "access",
  "iat": 1659878703,
  "exp": 1659879603
}

To achieve the desired output without the UserRole model, it should look like this:

{
  "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
  "username": "bl4drnnr",
  "roles": [ { "value": "USER" } ],
  "type": "access",
  "iat": 1659878703,
  "exp": 1659879603
}

I attempted to use the exclude property in Sequelize, but it seems to only work with fields, not models. So, how can I exclude the UserRole model from the database request?

Answer №1

One way to accomplish this is by using the through option with an empty array of attributes:

async fetchUser(conditions: object) {
  return await this.dataStore.locate({
    where: { ...conditions },
    include: [
        {
          model: Role,
          attributes: ['value'],
          through: {
            attributes: []
          }
        }
      ]
  });
}

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

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Generating Encrypted Passwords in PHP Login Page

Currently, I am facing an issue with creating a login page that connects to my server and verifies if the hashed (SHA256) database password matches the input password on the login page. Unfortunately, I have not been successful in making it work. In the e ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

How come Typescript claims that X could potentially be undefined within useMemo, even though it has already been defined and cannot be undefined at this stage

I am facing an issue with the following code snippet: const productsWithAddonPrice = useMemo(() => { const addonsPrice = addonsSelected .map(id => { if (addons === undefined) { return 0} return addons.find(addon => addo ...

Is there a way to omit type arguments in TypeScript when they are not needed?

Here is a function I am currently working with: function progress<T>(data: JsonApiQueryData<T>): number { const { links, meta } = data.getMeta(); if (!links.next) { return 1; } const url = new URL(links.next); return parseInt(url ...

Can HTML variables be accessed in lines of code before they are declared in HTML?

In line 1 of my code, I am trying to access the rowData variable which is declared in the second HTML line. However, I keep getting the error message "Property 'rowData' does not exist on type 'AppComponent'" for that line. Strangely, t ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Cypress terminal issue: Cannot find property in 'cy & CyEventEmitter' type

Tech stack: Angular v15 and Cypress V12 Despite successful runs of my component and end-to-end tests, I encounter peculiar terminal errors while running the tests. The issue could potentially stem from my Cypress configuration for shared commands. Here ...

Is there a way to customize the appearance of a MUI5 Tooltip using emotion?

I went through the information in this Stack Overflow post and experimented with the styled method. The code snippet I used is as follows: import * as React from 'react'; import { styled } from '@mui/material/styles'; import Tooltip, { ...

Tips for creating a typescript module definition that exports a module dependency as one of its members

Let's consider a particular situation: I am in the process of creating typescript definitions for two commonJS modules, A and B. Module B has a dependency on module A, and to make things easier, B directly exports A as a property B.A so that users do ...

Change the color of active buttons on dynamically generated buttons

My current challenge involves getting a button to stay active when pressed, especially when dealing with dynamically created buttons. Here is my current setup: <Grid container sx={{ padding: "10px" }}> {Object.values(CATEGORIES).map((c) => { ...

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...

Tips for simulating a configuration dependency using Proxyquire in TypeScript

Within my codebase, there exists a config.ts file that contains the following method: // Config interface is utilized to specify expected values export default function getConfig(): Config { return {amount: 50} } In a specific class located at ../src ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

What is the best way to access a variable from script A within script B using TypeScript?

I am looking to extract a variable from another script in order to generate the subsequent section of the page based on this data. Below is the code snippet that retrieves data from an API: import Axios from "axios"; import React from "reac ...

Choose exclusively the numeric digits from the text

Within my text field lies valuable information, including the following details: sch hcbhsc hscbshcbc xxxxxxxx sgxfag jdhajdh; dchbdbc bdcbdh bchdbd xx/xx-xxxx/xx svdhs sbjbsc bdchbdc jncjdnc jbcjb xx/xx-xxxxx/xx gcvsgc jcbjsb dchjbd bhjcbdcb bdcbcd ...