Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}.

For instance, an event could be classified as {genre: "music", subGenre: "jazz"}, and {genre: "music", subGenre: "blues"}. These genre subdocuments are added to the "genres" array in the Event document within the database, as specified in the event.js model file.

Now, in my node application (refer to query.ts), I am attempting to create a query that enables users to search for events based on their genre preferences.

Key points:

  • An Event is associated with an array of genres in the database,
  • The user's preferences consist of an array of genres within the application.

I aim to devise a mongoDB query that fetches all Events having at least one matching {genre, subGenre} combination between the two arrays.

After exploring the $in Query Selector in the mongoDB documentation, it appears like I might need to utilize it. However, I am unsure how to construct a query programmatically that incorporates all values in the "searchGenres" variable defined in query.ts.

Thank you in advance for your feedback.


event.js: Mongoose definition for 'Events' in mongoDB - excerpt:

let mongoose    = require('mongoose');
let EventSchema = new mongoose.Schema({
  genres: [
    {
      genre:      String,
      subGenre:   String
    }
  ]
)};
module.exports =  mongoose.model('Event', EventSchema);

query.ts:

import mongoose   = require('mongoose');
let Event         = require ('../models/event');

class Genre {
  genre:      string;
  subGenre:   string;
  
  constructor (gen: string, sub: string) {
    this.genre      = gen;
    this.subGenre   = sub;
  }
}

async function runQuery()
{
  let searchGenres : Array<Genre> = new Array<Genre>();

  // Populate searchGenres with some data here... e.g.
  const searchGenre1 : Genre = new Genre ('music', 'jazz');
  const searchGenre2 : Genre = new Genre ('music', 'rock');

  searchGenres.push(searchGenre1);
  searchGenres.push(searchGenre2);

  // Query logic goes here:
  // Return all events from the database where the 'genres' array
  // in the document matches any element in the searchGenres array
  // specified above.

  const events = await Event.find ({
                                     'genres': {?help? }

                                  });
}

Answer №1

Today, I dedicated some time to educating myself and was able to devise a satisfying solution - adding the following code snippet to the end of query.ts:

type GenreQuerySelector = { genres: { $elemMatch: { 'genre': string; 'subGenre': string; }; }; };

let querySelectors : Array< GenreQuerySelector > = new Array< GenreQuerySelector >();

for (let genre of searchGenres) {

    const genreQuery : GenreQuerySelector = {
        genres: {
                    $elemMatch: {
                                    'genre':    genre.genre,
                                    'subGenre': genre.subGenre
                                }
                }
     };        
     querySelectors.push(genreQuery);
};

const events = await Event.find  ({ $or: querySelectors }).exec();

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

The function `canvas.toDataURL()` does not produce an image as output

When I expect the image to return mirrored, it instead shows up as a black image. <!DOCTYPE html> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <bo ...

Tips for utilizing the combined value of two fields while searching for a document in MongoDB

In my search for an account with targetAmount >= totalAmount + N, I have a variety of accounts to sift through. { "_id": { "$oid": "60d097b761484f6ad65b5305" }, "targetAmount": 100, "totalAmount&q ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The communi ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Is window.open exclusive to Firefox?

Apologies if this question has been asked before! I am experiencing some issues with my Javascript code. It works perfectly in Firefox and opens a pop-up window as expected. However, in IE 9 it does nothing, and in Chrome it behaves like a link and change ...

Calculating the total sum of values in a table using Jquery

Can anyone help me calculate the sum of input values from a table using HTML and jQuery? Here is my current code: HTML: <tr id='saved1'> <td><input class='qty'/></td> <td><input class='price&apo ...

Obtain embedded objects within a MongoDB record based on conditions specified in the parent and child linked documents

Below is a description of a user structure in MongoDB document format. { "_id" : ObjectId("588db8c76b1d3032105a8faf"), "uid" : "123456", "groups" : [{_id : "1", "uid" : "123"}, {_id : "1", "uid" : "258"}, {_id : "1", "uid" : "296"}], "conn ...

enhancing the types of parameters in a function declaration without relying on generics

My goal is to improve developer experience (DX) by expanding the types for parameters in a function signature. I want the tooltip when hovering over the following function to provide more detailed information: type Props = { a: number; }; const func = ( ...

Attempting to eliminate the padding from the unordered list (ul) element within the pop-up box

Upon clicking the chip with chipName="button test IPA", a popup window appears. I am attempting to remove the padding from the ul tag within that popup. The issue I'm facing is that I cannot locate the ul tag in my HTML or JSX code. I have assigned a ...

Could having a large collection in mongoDB impact the performance of other collections?

As I delve into saving files in my application, there's an ongoing debate on whether to store them in the filesystem or database. After careful consideration, I have decided to save the files in the database. The database system I am using for this p ...

What is the best way to dynamically search and retrieve data from a JSON object in Angular?

I am facing a challenge with my Angular (v. 1.6.3) app where I have fetched a JSON object containing stock price data. The structure of the JSON object only allows querying using brackets, with each key being a string that may include spaces, parentheses, ...

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

What approach can be taken to establish a dependency between an AngularJS controller and a value that is retrieved through ajax and loaded onto the root

I have an app that loads like this: app.js file: angular.module('App', []).run(['$rootScope', '$q', 'SessionManager', 'EndpointService', function ($rootScope, $q, SessionManager, EndpointService) { $r ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

Creating a multipart/form-data request using JavaScript/jQuery

After much searching and experimentation, I have been trying to understand the process of constructing a request to be sent using something similar to $.ajax({ contentType: "multipart/form-data", type: "POST", data: ...

The datepicker in Vue.js is experiencing a limitation where it does not allow for the default value of an

I incorporated the vue-date-picker for date picker functionality in my input fields because it perfectly aligned with all of my requirements. The issue I encountered is that when loading the page, I attempted to pass a default value from the database, but ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...