Retrieve a specific set of objects with Mongoose, extracting only the objects contained within it

Picture this scenario:

{
  "_id": "2020 Standings",
  "DriversChampionship": [
    {
      "_id": "5fd3966d2769dc12dc010475",
      "driverName": "Lewis Hamilton",
      "driverTeam": "Mercedes AMG",
      "driverPts": "230"
    },
    {
      "_id": "5fd3966d2769dc12dc010476",
      "driverName": "Sebastian Vettel",
      "driverTeam": "Ferrari",
      "driverPts": "161"
    }
  ],
  "ConstructorsChampionship": [
    {
      "_id": "5fd3966d2769dc12dc010489",
      "teamName": "Mercedes AMG",
      "teamPts": "230"
    },
    {
      "_id": "5fd3966d2769dc12dc01048a",
      "teamName": "Ferrari",
      "teamPts": "161"
    }
  ]
}

In the Routes folder, I have created a GET request as follows:

router.route("api/standings/:arrayName")
    .get(getStandingsArray);

How can Mongoose find and send a res.json response with only the array that matches the :arrayName?

Let me illustrate with an example:

If I access the route

http://localhost:4000/api/standings/DriversChampionship

The controller extracts the :arrayName using...

const arrayName = req.params.arrayName

// arrayName = DriversChampionship

and then retrieves and displays this particular array of objects using modelName.find()...

"DriversChampionship": [
    {
      "_id": "5fd3966d2769dc12dc010475",
      "driverName": "Lewis Hamilton",
      "driverTeam": "Mercedes AMG",
      "driverPts": "230"
    },
    {
      "_id": "5fd3966d2769dc12dc010476",
      "driverName": "Sebastian Vettel",
      "driverTeam": "Ferrari",
      "driverPts": "161"
    }
  ]

I'm still trying to figure out how to accomplish this with Mongoose.

Any suggestions or ideas?

Feel free to ask if any part of my explanation is unclear

Thank you!

Answer №1

To obtain the desired field (such as 'DriversChampionship' in this case), you can utilize the select method. Here's how:

var result = modelName.find({}).select('DriversChampionship -_id');

If you want to make it more dynamic, you can do the following:

const fieldName = req.params.fieldName
var result = modelName.find({}).select(`${fieldName} -_id`);

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

Processing of JSON data and manipulation of string constants

Looking for help with using a string constant in JavaScript? MyString.START = 'start'; If you have a JSON object named input and want to access a property based on the value of MyString.START, the syntax would be input[MyString.START]. Does th ...

Encountering a RangeError when transmitting OpenLayers3 event via AJAX

An error is appearing in the chrome console stating: RangeError: Maximum call stack size exceeded The code I am using is as follows: draw.on('drawend', function(evt) { var fe = evt.feature console.log(fe); ...

Step-by-step guide on making a duplicate of a Search bar

I have a search field in my application that I want to duplicate. The goal is to create two identical search fields, one on the left side of the page and another on the right side. How can I achieve this using JavaScript? Here is my JavaScript code: doc ...

Utilizing Recursive AJAX Request in JQuery and SharePoint to Retrieve All Entries from a Specific SharePoint List

I am having trouble retrieving all items from a SharePoint List using a recursive ajax call on the REST-API. Despite being able to load all the data into an array, my code for calling the Ajax functions within the .then() doesn't appear to be function ...

Utilizing jQuery to invoke a function at the conclusion of another function's execution

Can someone explain how jQuery can achieve the following? $('.test').css().otherThing...... etc I'm attempting to accomplish this with prototype: var myPrototype = function () {}; myPrototype.prototype.console1 = function() { console.lo ...

Changing the title of a jQuery DataTable with a button click

Within my view, there are two input fields, a button, and a table that is utilizing jQuery DataTables. The datatable has a print functionality integrated into it. I am attempting to customize the title of the print page based on the values inputted into ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Importing a MongoDB dump: A step-by-step guide

Successfully dumped a MongoDB: $ mongodump -h ourhost.com:portnumber -d db_name01 -u username -p I am having trouble importing or exporting it to a test server and need some assistance. I have attempted a few methods: $ mongoimport -h host.com:port -c ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

What is the solution to deselecting all other options when selecting one in an <input type='radio'>?

As a newcomer to Vue/Nuxt, I'm currently facing an issue with a group of radio inputs that do not unselect when another option is chosen. After some investigation, it seems like the problem may lie within this specific code snippet below. My focus is ...

Tips for accessing the scope bound to a template within a directive's link function

In HTML, I include an ID inside a directive: <my-product data="id"></my-product> In JavaScript: angular.module('App', []) .controller('Controller', ['$scope', function($scope) { $scope.id = 'productDiv& ...

The AJAX functionality seems to be failing to load the additional JavaScript and CSS files

Using a brief AJAX code, I fetch Facebook content from a PHP file where class="gallery-img-link" is defined as <a> and class="img-responsive img-thumbnail" is declared as <img>. The issue arises when attempting to load these classes via an AJA ...

Blinking magic of dynamic rendering with NextJs

I am facing some challenges with dynamically importing a component in my NextJs application. I am attempting to import the Froala text editor, which is supported for React. However, when I try to import it, I encounter errors stating that window is not def ...

Unable to set up cordova using npm version 5.6.0

I'm encountering issues trying to install Cordova on my Linux system (Deepin 15.5). Can anyone offer assistance? $ sudo npm install -g ionic /usr/local/bin/ionic -> /usr/local/lib/node_modules/ionic/bin/ionic npm WARN optional SKIPPING OPTIONAL ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

I'm having trouble getting the conditional ngClass to function properly in my specific scenario

<li ng-class="{selected: 'checked==true'}" ng-repeat="item in data"> <span>item.name</span> <input ng-model="checked"/> </li> Is there a way to dynamically add the 'selected' class only after clicking on t ...

Unable to view Bootstrap Icons in Gulp 4

I recently integrated the new bootstrap icons npm package into my project using Gulp 4, the latest version. Everything was installed successfully and was working smoothly. However, I encountered an issue when trying to declare the icon in my index.html fi ...

React is re-rendering the identical div elements once more - Delving into the concept of

After reading about reconciliation in the React documentation, an interesting scenario crossed my mind. In my examples, I have code that involves using a button element to toggle a boolean value on click event. Based on this value, the code utilizes a ter ...