Home > Software design >  Why Does Mongoose Query Return an Empty Array
Why Does Mongoose Query Return an Empty Array

Time:03-03

Hello I have looked at similar questions to the one I asked but none of the resolutions fit my issue. I am developing an api. I get the request payload from client and a response payload on the server side when I send response using payload, its when I try to use a mongoose query(search) that I run into an issue with a empty array. All things checkout such as:

Connected to mongoose, Database does exist, Collection exist and has default name of my interface/class.

To be assured I had the correct db name I let it be created when I did mongoose.connect('mongodb://localhost/database for first time

My mongoose schema file exist. It takes on the default name on the class and it is singular. I have included a small snippet. Can someone help tell me what I'm doing wrong,

Interface

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

livesearch.js Schema

const mongoose = require('mongoose');

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

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

product.js

router.post('/getProducts',  async(req, res) =>{
      
    let payload=req.body.payload;//server needs to extract payload property
     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) empty array
     //Limit search to 10
       search = search.slice(0, 10);

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

Database and collection

> show collections
productLiveSearch
products
>

CodePudding user response:

Your collection likely doesn't have anything in it; you need to populate it first for a query to return with values.

  • Related