typeorm querybuilder: retrieve nested relations only

Among the entities I'm working with are:

Group {
    id: number;
    name: string;
    persons: Person[];
}

Person {
    name: string;
    items: Item[];
}

Item {
    name: string;
    active: boolean;
}

What I have at my disposal: an array containing group id's groupIds.

My Objective: To obtain an array of Item objects, specifically those that belong to groups with IDs present in the given array and have the property active set to true.



I attempted to construct a query builder as follows:

this.groupRepository.createQueryBuilder('group')
                      .innerJoin('group.persons', 'persons')
                      .innerJoinAndSelect('persons.items', 'items')
                      .where({'items.active': true, 'group.id': In(groupIds)})
                      .getMany();

Unfortunately, this approach only returns an array of group objects without any associated relationships that contain valid item entries.

What modifications should be made to achieve this desired result, ideally within a single query?

Answer №1

Consider implementing the following code snippet:

this.groupRepository.createQueryBuilder('group')
   .leftJoinAndSelect('group.persons', 'persons')
   .leftJoinAndSelect('persons.items', 'items')
   .where('items.active =:active', {active: true})
   .andWhere('group.id IN (:...groupIds)', {groupIds})       
   .getMany();

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

How can I achieve the same functionality as require('deferred') using "import from" in Node.js versions 13 and higher?

I am not a Node expert, but from what I understand, the use of 'require' instructions is no longer supported by default in Node versions higher than 12. I am currently in the process of migrating an old version app and have come across the import ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Experiencing a repetitive occurrence of the error: "SyntaxError: Encountered an invalid or unfore

I've encountered a persistent error when attempting to execute my index.mjs file. Here is the content of my index.mjs file: import WebSocket, { WebSocketServer } from "ws"; import http from "http"; import express from 'express ...

How can we utilize extension in Jade templates?

I have recently started working on a new project involving Jade, Express and Node.js. It's my first time diving into any of these technologies. One of the tasks I'm tackling is creating jade templates. Currently, I have successfully created a la ...

Execute a SQL query every half minute to retrieve a count, and store the results in a designated file

As I work on creating a website, I have incorporated a database that allows users to input data in the form of votes. To enhance user experience, I want to display a counter in the header showing the total number of votes cast so far. However, considering ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Node.js TCP server sequentially processes incoming packets

In my Node.js application, I am utilizing a TCP server to receive and handle packets. The server should expect to receive two specific types of packets: "create" which is responsible for creating an object in a database. This process involves ch ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

Enabling logging for the Mapnik SQL query while generating the map

Currently, I am utilizing the npm package known as Mapnik in conjunction with PostGIS. My goal is to include logging functionality that captures the SQL query executed by Mapnik, along with the value of the bbox parameter, when executing the render() funct ...

I am looking for a way to showcase buffer data as an image in a React application

Need help with displaying images in a react application? function App() { const [imageData, setImageData] = useState(); useEffect(() => { const fetchData = async () => { const response = await axios.get('http://localhost:8000' ...

Make sure to add the local private NPM dependency before running the prepublish script

Within my application package.json file, I am referencing a local private NPM dependency like this: "core-module": "file:///Users/myuser/Documents/projects/core_module" My goal is to have the local private dependencies (such as core-module) automatically ...

Tips for accessing subdocument data from Mongoose in the frontend using ReactJs

I am looking to retrieve comprehensive information about a collection known as "commercant", which includes another collection called "personne" in the front end using ReactJs. Although Postman returns all data, the front end is struggling to interpret the ...

Troubles with rendering output of compiled program when run within a Dockerized environment

My website features a file upload and submit button. When a user uploads a C++ file and submits it, a Docker container is started to compile and run the code. The objective is to showcase the program's output on the web server. Initially, I experience ...

Is there a way to prevent Express from automatically converting the '+' character in query strings to spaces when making a GET request?

During a GET request, I am including specific parameters in the query string such as HOST?email=john**+[email protected]. However, when trying to retrieve these values in my Node Express server using req.query.email, the value received is 'john [ ...

Sorry, but I am unable to complete this task as it involves rewriting content that has been provided by you. How about

Attempting to retrieve the date from a Unix timestamp with a timezone using moment-timzone var moment = require('moment-timezone'); let date = moment.tz('Asia/Kolkata').unix(dateInUTC).format('YYYY-M-DD-H-mm-s') Encoun ...

Steps to resolve npm ERR! Unexpected end of JSON input error when parsing near '...m":"b569e8103ed5b2ad3'

During my attempt at installing electron, I followed the command provided in the documentation: npm install electron --save-dev npm ERR! Unexpected end of JSON input while parsing near '...m":"b569e8103ed5b2ad3' npm ERR! A detailed ...

The functionality of Everyauth seems to be malfunctioning in the latest version of Express

Currently, I am utilizing nodejs, express 4, and everyauth for social network authentication. I have encountered an issue where upon clicking Accept from Google and getting redirected back to my /, an error message appears: _http_outgoing.js:335 throw ne ...

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

Guidelines for establishing a dynamic reference in Node.js with MongoDB

I am currently working on a nodejs project and I have encountered an issue. I have a mongo schema that consists of a list of objects: players: [{ type: Schema.Types.ObjectId, ref: 'User' }] However, the "ref: 'User'" isn&ap ...

Secure user authentication is essential for the proxy application built on Express using NodeJS

I currently manage two servers: Server A - Utilizes Express/FeathersJS and is accessible to the public. It is secured with JWT for authentication. Server X - A Django application that is not available publicly and does not require any type of authenticati ...