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
>