Discover all NestJS elements sorted by category

I am currently working with an entity called BookEntity:

@Entity()
export class BookEntity {
    @PrimaryGeneratedColumn()
    @Generated("increment")
    public id: number

    @CreateDateColumn()
  public createdAt: Date

    @Column()
    public title: string

    @Column()
    public author: string

    @Column({ type: "simple-array" })
    public category: string[]

    @Column({ default: "" })
    public cover: string

    @Column()
    public issueDate: string

    @Column({ default: 0 })
    public liked: number

    @Column({ default: 0 })
    public downloads: number

    @Column({ default: 0 })
    public views: number

    @Column({ type: "simple-array" })
    public path: string
}

My goal is to filter entities based on the value in the category column. For example, if an entity has categories ["test1", "test2", "test3"], I would like to retrieve all entities with the category "test2". Can someone guide me on how to achieve this?

I have already implemented a service to fetch a paginated list of all book_entity:

    public async getBooks(page: number): Promise<PageDto<BookEntity>> {
        try {
            const queryBuilder = this.bookRepository.createQueryBuilder("book_entity")

            queryBuilder.take(10)

            const itemCount = await queryBuilder.getCount()
            const { entities } = await queryBuilder.getRawAndEntities()

            const pageData = new PageDto<BookEntity>(entities, itemCount, page)

            return pageData
        } catch (error) {
            console.log("Getting books error: ", error)
        }
    }

However, I am unsure about how to modify this service to filter by category. I understand that the queryBuilder has an .orderBy method, but I am uncertain about its usage for my specific requirement.

Answer №1

To narrow down your query results, you can utilize the where or andWhere methods (especially useful for multiple filters).

const queryBuilder = this.bookRepository.createQueryBuilder("book_entity")

queryBuilder.where('book_entity.category IN (:...category)', { category: ['"test2"'] })

For more complex filtering scenarios, please visit https://github.com/../select-query-builder.md#adding-where-expression.

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

jQuery blueimp File Uploader: Transferring multiple files to the server on Internet Explorer

After customizing the demo for my Rails application, I encountered an issue with the plugin in Internet Explorer. While it works smoothly on Chrome and Firefox, in IE (all versions) it fails to upload all but one file when multiple files are selected, and ...

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

Should I use a single directive with ng-if statements in AngularJS, or opt for two separate directives?

Question about optimizing performance in Angular JS. I am using ng-repeat to display a list of search results. Each search item is extracted using a directive/template. Should I wrap two directives with ng-if statements or use one directive with multiple ...

Is there a way to remove createdAt and updatedAt from every query in Sequelize?

Currently, I am utilizing Node 14 and Sequelize to model an existing Postgres database. The tables that have already been created do not contain the createdAt or updatedAt columns, so my intention is to set up Sequelize in a way that it will never attempt ...

Creating and accessing a temporary binary file using Node Js

Challenge I have been working on integrating the Google Text To Speech (TTS) service to save a generated binary audio file to Google Cloud Storage (GCS). Considering that saving a local binary file in Firebase's Cloud Functions environment may not b ...

How can we verify if a React component successfully renders another custom component that we've created?

Consider this scenario: File ComponentA.tsx: const ComponentA = () => { return ( <> <ComponentB/> </> ) } In ComponentA.test.tsx: describe("ComponentA", () => { it("Verifies Compo ...

Limiting style changes to specific labels in Highcharts

Can someone assist me in bolding only the middle elements of a highcharts x axis? I have tried to apply a solution in the provided fiddle but it doesn't work as expected. Specifically, I am looking to bold the x-axis labels for June or July. http://j ...

Receiving error in TypeScript while using the 'required' attribute in the input field: "Cannot assign type 'string | undefined' to parameter expecting type 'string'"

In my TypeScript code, I am currently in the process of transitioning from utilizing useState to useRef for capturing text input values. This change is recommended when no additional manipulation necessitating state or rerenders is required. While I have ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

The "discord.js" module is throwing an error stating that the property for

Currently, I am in the process of developing a Discord bot using discord.js. As part of this project, I am incorporating JSON functionality to store information for individual users in a separate file. However, I have encountered an issue where an error me ...

"Inquiry on Python's general syntax: transitioning from a statically typed language to a dynamically typed one

I'm diving into the world of Python and have a question regarding Python syntax. I'm transitioning from theory to practice and looking to translate a TypeScript class into Python. class Category { id: number; type: 'shop'|' ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...

Unable to set I18n locale for Vee-Validate in VueJS is ineffective

In my VueJS Application, I am implementing form validation using the Vee-Validate plugin. With multiple languages supported in my app, I have integrated I18n for localization. Each plugin is stored in separate files within the plugins folder and then impor ...

Transferring Javascript properties to a new instance

In the realm of Javascript, let's consider a scenario where we have the following structure: obj1.prop1.prop1_1.prop1_1_1 = 3; Now, when this code is executed, the value 3 should be set in the same pathway within obj2. Essentially, it should mirror ...

Add a prefix to all constructors in Ionic 3 code

Is there a way to automatically redirect if not logged in on all pages without having to duplicate the code? constructor(private appCtrl: AppController) { this.appCtrl.redirectIfNotLoggedIn(); } ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

Using the Protractor tool to close a window popup

this.compareProductTitles = async function(title) { await browser.getAllWindowHandles().then(function (handles) { handles.forEach(function (handle) { console.log(handle.toString()); browser.switchTo.window(handle); ...

When utilizing the array.push method, new elements are successfully added, however, it appears to also overwrite the last object

I'm encountering a strange issue where every time I push an object to the array, the array's length increases as expected. However, the object that I push last ends up overriding all other objects. I can't seem to figure out my mistake, so p ...

Angular is a programming framework that uses pipes to place an underscore below a

In order to get the first letter and add an underscore underneath, you can use the following code: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'underlineFirstLetter' }) export class underlineFirstLetterPipe im ...

A step-by-step guide on resolving the issue "Error: listen EADDRINUSE: address already in use :::5000" in the event of an error

node:events:495 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE: address already in use :::5000 at Server.setupListenHandle [as _listen2] (node:net:1817:16) at listenInCluster (node:net:1865:12) at Server. ...