Retrieve nested subarrays using ExpressJS with MongoDB

Looking to set up a separate route in my API to access a sub-array from a nested array using ExpressJS.

Categories Array:

const Categories = [
{
    _id: 's654fs54s6d4f'
    title: 'category 1',
    SubCats: [
        {
            _id: 'jhgfsf68746'
            name: 'subcat 1',
            image: '/assets/images/vr-box-6203301_1920.jpg',
        },
        {
            _id: 'vb40n5b4vn'
            name: 'subcat 2',
            image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
        },
    ]
},
]

Category Model:

import mongoose from 'mongoose'

const Catschema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    image: {
        type: String,
        required: true,
    },
})

const CategorySchema = mongoose.Schema(
    {
        title: {
            type: String,
            required: true,
        },
        SubCats: [Catschema]
    },
    {
        timestamps: true,
    }
)

const Category = mongoose.model('Category', CategorySchema)

export default Category

Category Controller:

This function would return the entire array.

const getCategories = asyncHandler(async (req, res) => {
   const categories = await Category.find({})
   res.json(categories)
})

I am looking to specifically return the 'SubCats' array.

Tried this code but received an error stating "SubCats is not defined".

const getSubCategories = asyncHandler(async (req, res) => {
   const subcategories = await Category.find({SubCats})
   res.json(subcategories)
})

Answer №1

retrieve() provides a set of data and requires an input object to search the database. Your syntax Category.retrieve({SubCats}) should actually be written as

Category.retrieve({SubCats: SubCats})
, where SubCats needs to be defined.

To fetch Categories with only SubCats, you might want to consider using

Category.retrieve().select('SubCats')
.

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

avoid inserting into a specific field with a specific name

I am trying to add a picture next to a specific name, but I am facing issues as there is no option for inserting it. This is how my table looks: https://i.sstatic.net/RRaTb.png How can I insert a picture in front of a particular name? The content of my ...

Unknown and void

undefined === null => false undefined == null => true I pondered the logic behind undefined == null and realized only one scenario: if(document.getElementById() == null) .... Are there any other reasons why (undefined === null) ...

Is it time to reconsider using multiple Angular filters in ng-repeat loops?

I am in the process of developing a car rental website using Angular framework. In the section where users select cars, they should be able to filter based on various attributes like 4x4 capability, automatic or manual transmission, and different categori ...

"Input numbers into the box provided to calculate the total sum

I have a problem with my code that involves prompting the user to input two numbers and then adding them together. However, when I run the code, it concatenates the numbers as strings rather than performing addition. Here is the code snippet in question: ...

Discover a technique to display every individual "echo" statement from PHP in sequence, rather than waiting for the entire script to finish executing

I have developed a PHP script that takes some time to execute and displays multiple "echo" statements as the progress is being made. The script connects to an FTP server, deletes all contents, and then uploads new files. Everything is functioning correctly ...

There seems to be an issue with the ejs not linking up correctly

Currently, I am facing an issue with linking my CSS file to EJS in a simple Express Node.js project. Both files are located in the same folder as shown in the image below. I have also included app.use(express.static(__dirname + "/website")). Des ...

Tips for building a custom template using express-handlebars

I seem to be encountering an issue with my exphbs function as it keeps indicating that it does not exist. Despite attempting npm install express-handlebars@latest, npm install express-handlebars, and npm install --save express-handlebars, none of these me ...

"Delve into the art of utilizing negative space between elements with

Looking to implement hover detection between rows in a grid container, rather than on individual items. The number of items in the container and per row may vary. https://i.sstatic.net/yBgKI.png It's important to note that the item count in the cont ...

Creating a div anchor tag within a component in React

Forgive me if this question has already made its rounds on the internet, but I can't seem to get anything to work in my favor. I was under the assumption that all you had to do was append the # + div id at the end of a URL to navigate to a specific d ...

What causes my JavaScript setTimeout operation to resemble a setInterval?

For an exercise, I created a simple function to display a "binary clock" that updates every two seconds instead of one. This function is actually a modified version of similar code that works within an HTML form (updating a value repeatedly). Below is my ...

Check out the most recent N records by utilizing MongoDB Compass

I am looking to efficiently view the latest N documents in a MongoDB Compass collection that is very large. Scrolling through all the documents is not practical due to the size. If I knew the syntax within Compass, I would use .skip(total - N) to achieve ...

Set up a Pinia store with a specific data type

Note: I am a beginner in JavaScript I am currently working on synchronizing an object with a Pinia store and a Python REST API. My goal is to define a type just once without having to duplicate it in the store. export const useTicketStore = defineStore(&a ...

What is the method for determining the new point coordinates and direction vector after a rotation of degrees in three.js?

How can I determine the coordinates of point A to H after rotating a certain number of degrees and aligning them with direction vector (-42, 51, 11) using three.js? Thank you in advance for your help and please forgive any mistakes in my English. Best reg ...

I am having trouble comprehending this JavaScript code, could someone provide me with assistance?

Currently delving into the world of JavaScript functions and stumbled upon this code snippet with the following output: Output: "buy 3 bottles of milk" "Hello master, here is your 0 change" function getMilk(money, costPerBottle) { ...

Error: Unable to access 'amtSavingsInput' variable before it has been initialized

I encountered an issue with form3/chart3 while trying to replicate the success of form1/chart1 and form2/chart2. Despite following the same steps and structure, form3/chart3 seems to be malfunctioning. The error message I'm receiving is "Uncaught Refe ...

Error in Node JS: When attempting to use "require", a ReferenceError is thrown

After deciding to utilize a MySQL database, I proceeded by installing MySQL using the command npm i mysql. Following the installation, I included the line of code below in order to begin utilizing it: var mysql = require('mysql'); However, upon ...

Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false. To demonstrate this, I have created a fiddle below. ...

Tallying outcomes using JavaScript

I encountered a particular challenge: I have designed a table for user interaction, with results displayed at the end of each row. Just out of curiosity, I would like to count how many results are present in the table without performing any calculations. I ...

How to choose the desired day within a specific month when creating a calendar from scratch?

Hi there! I need some assistance. I'm currently working on enhancing a calendar by adding an extra feature. The idea is that when the user selects one or more days, those specific day(s) should be highlighted. However, I'm facing an issue where s ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...