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

During the process of executing a HTTP GET request, an output of "OPTIONS https://riskassessmentidtypes.px-npe01.com/customer-credit/ 0 ()" was obtained

I am currently engaged in an internal project involving Angular 5. Our team is working on making an HTTP GET call to a URL located within the PCF environment. However, during this process, I encountered the following console message: OPTIONS 0 () Progre ...

Error in StoryBook addon-docs: "No props discovered for this particular component" when utilizing TypeScript

Encountering an issue with a TypeScript and StoryBook project: The table displaying component properties is not generated nor visible in the StoryBook "Docs" tab on a TypeScript-based project setup. Instead of the expected table, a message saying "No pro ...

Exploring within the Angular submodule path

I am facing a challenge with nested modules having different URL prefixes. I want to navigate within one module without specifying the prefix, making it accessible regardless of the prefix. Here are the routes for my app.module: const APP_ROUTES: Routes ...

Angular material chips showcase a row of five chips

I am working with the basic mat-chips from angular material and I want to arrange them in rows of five without increasing their size: Chip1 Chip2 Chip3 Chip4 Chip5 ..................(space left) Chip6 Chip7 Chip8 Chip9 Chip10 ...............(space le ...

Error encountered when attempting to update item in DynamoDB: UpdateExpression is invalid due to a syntax error with the token "like"

I am attempting to update a nested field within the "users" table in DynamoDB called "general" using an Express server hosted on a Lambda function. The "general" field contains subfields such as "gender" and "about". Below is the PATCH request code I have ...

Having issues transferring files from Angular 8 to NodeJS

After successfully implementing a component for drag and drop file functionality using Angular, I encountered an issue when trying to create a service for server requests. The DragDropDirective is as follows: // Code for DragDropDirective import { Direct ...

Pass the response from a MySql query executed in ExpressJS to a basic JavaScript file that is responsible for modifying the

I am currently utilizing ExpressJS as my server and MySql as my local database. However, I am facing a challenge in retrieving data from a specific table and sending the query result to either a vanilla JS file or directly editing HTML through NodeJS. Her ...

Where is the assistant "select" function?

I've been working on displaying the selected option from MongoDB. Despite multiple attempts and researching various sources, I keep encountering the following error: "Error: Missing helper: 'select'". Below is the contents of my handlebar_h ...

Getting the perfect typings installed from DefinitelyTyped

In my current attempt to install typings (version 1.3.2) for the malihu-custom-scrollbar-plugin, I am facing an issue with some wrong type identification error (Error TS1110: Type expected). This error is caused by the use of string literal types syntax li ...

Upon being provided with a route param, the response will be

For my current project using Express, I want to implement Reddit-like functionality where appending ".json" to any URL will return JSON data instead of the rendered template. To set up the rendering engine in Express, I am using Jade. Here is how I config ...

Creating a non-editable form or text field upon clicking the Submit button

<form [formGroup]="calculateForm"> <div class="form-group row"> <p for="inputFrom" class="col-sm-4">Distance traveled ...

What is the correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array. Array cars = [{ id: 1, ...

Tips for storing headers in NODE.JS?

Recently started learning NODE.JS Looking for some guidance. When I try to execute the command below: npm install --save express-handlebars I encounter the following error message: + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Tips for handling dropdowns within a formarray in Angular

https://i.stack.imgur.com/f7V4H.pngI'm currently attempting to dynamically select a dropdown value, but the issue I'm encountering is that when I select a value in the dropdown, I get an object out of it. From this object, I am trying to set the ...

Utilizing the React TypeScript useContext hook with useReducer for state management

I'm struggling to identify the type error present in this code snippet import React from 'react'; interface IMenu { items: { title: string, active: boolean, label: string }[] } type Action = | { type: 'SET_ACTIVE&a ...

managing error responses between express and react

I'm encountering an issue with sending an error response from an Express API call when a user adds a non-unique category or fails to specify a category at all. Although I am able to successfully save the category in the database and return a proper re ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

Is there a way to convert a JSON input object to a model class using TypeScript in a Node.js application?

Currently, I am developing my Node.js server using TypeScript and the express framework. Here is an example of what my controller and route looks like: export class AuthController { public async signUpNewUser(request: Request, response: Response) { ...