What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem.

When handling request and response payloads in my API, everything seems to be working fine except when I attempt to use a mongoose query for searching. I keep running into issues with receiving an empty array as a result.

I have checked all the necessary components such as:

  • Ensuring connection to MongoDB is established
  • Confirming that the database exists
  • Verifying that the collection exists with the default name of my interface/class

To double-check the database name, I let it be created by using

mongoose.connect('mongodb://localhost/database')
for the first time.

The mongoose schema file is in place with the default class name being used singularly. Below is a snippet of the interface:

export interface Products{
  _id: string,
  name: string
}
//imported in my service.ts

Here is the schema defined in the livesearch.js file:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Products', productSchema, 'products');

This is how the route is implemented in the product.js file:

router.post('/getProducts',  async(req, res) =>{
      
    let payload=req.body.payload;
     console.log("Payload", payload);
       
    console.log("Heading to search");
    let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*', 'i')}}).exec();
          console.log("Search", search); // returns empty array
     //Limit search results to 10
       search = search.slice(0, 10);

       //res.send({payload:load});  //this works
     
       res.send({payload:search});  
    
     
})

Confirmation of existing collections in the database:

> show collections
productLiveSearch
products
>

Answer №1

It appears that your collection is empty; you must add items to it before running a query in order to receive results.

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

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

In the case of an Angular application, what is the reason behind hotkeys not functioning in Chrome until the user actively engages with the webpage

When using Angular, I have set up various HostListeners to listen for keydown events: @HostListener('window:keydown', ['$event']) keyEvent(evt: KeyboardEvent) { console.log(evt) } I observed in the console logs that these listeners a ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Unable to make a POST request to the express API using the next.js API route (nextauth)

Currently, I have an express server running on port 8080 and my NextJS app running on port 3000. To handle user authentication, I am utilizing nextauth which involves sending username and password credentials to the express API on port 8080 for validation. ...

What could be the reason for receiving the error message "NgModule' is not found" even after executing the command "npm i @types/node --global"?

Even though I tried following the suggestions provided in this Stack Overflow thread, I am still encountering the error "TypeScript error in Angular2 code: Cannot find name 'module'". My development environment consists of Angular 5 and npm versi ...

Issue with the proper functionality of the this.formGroup.updateValueAndValidity() method in Angular 6

Currently, I am facing an issue where I need to add or remove validators in a formGroup's controls based on certain conditions. When I try to update the validators using `formGroup.updateValueAndValidity()` for the entire form, it does not seem to wor ...

Purge the localStorage every time the page is refreshed in Angular 2

After successful authentication, I am storing a token in localStorage. However, every time I refresh the page, I need to delete the token and redirect to a specific router. I'm struggling to find a way to achieve this in Angular, so currently I' ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

Developing Angular2 applications in Visual Studio Team Services (formerly known as Visual Studio Online)

Currently, I have an angular2 client integrated into a Visual Studio vNext (ASP.Net 5) project. During my attempt to create a build in Visual Studio Team Services, I encountered errors similar to this one during the build step: It appears that module &a ...

Obtaining additional information for Observable<Object[]>

I have a scenario where I am working with a service that returns Observable<Object[]>. Each Object in the array has a subObjectId property. My goal is to populate the object's subObject property with data retrieved from another service. How can ...

Unable to retrieve the attribute from the mongoose schema

After searching for an item in the database, I am able to find it and print it successfully. However, when attempting to access the attributes, they are showing as undefined. I have verified that the attributes are indeed defined because it does not break ...

What happens when two style() functions are passed into the query() function for Angular Animations?

As someone who is relatively new to angular animations, I have reviewed the angular.io animation documentation multiple times in order to grasp how everything functions. While I believe I have a decent understanding, there are certain scenarios that the do ...

Incorporate a dynamic form into an ngx-sortable control in Angular 6

Having difficulty with the layout implementation in Angular 6. A form component is dynamically added during runtime. Using ngx-sortable, I aim to have dynamic content within it, but am facing challenges with the setup. Implementing Sortable control: &l ...

Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example: import * as models from '../../view-models/models' ....... let parrot: m ...

express-session: include additional information in 401 error reply

I have been exploring express-session and am curious about the ability to include extra information in the 401 response that express generates when a session is not discovered. My goal is to differentiate between an expired session and a missing session, ...

Combining Two Related API Requests using Angular Observables and RxJS

If I have two API calls that return JSON: First call (rows): { {"row": 1, detailId: "a"} {"row": 2, detailId: "b"} } Second call (rowDetails): { details: { row details } } The task at hand is to fetch rows first, then iterate through each row o ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

navigating to a new page using Angular routing following a successful call to an API on an Express server

When using angular routing in a single page application, how can I redirect a page after an API call? Specifically, I want to redirect the user to the profile page after they have called the login API. However, my current method does not seem to be working ...