Fetch to Mongodb database returning an empty array

Hi, It is my first time using Mongodb, and I have built a simple backend with a server using Node.js and express to retrieve data from collections in Mongo. The backend is hosted at https://backend-production-0624.up.railway.app. I connect to this endpoint with a frontend application.

I have two collections with different data in which I want to retrieve - with two separate fetch requests.

The fetch request (which uses the endpoint /api/names) is retrieving data and showing it in the console of the front end.

However, the second fetch request (which uses the endpoint /api/mainInfo )is returning an empty array to my front end - even though there is data in the collection (which I can view in Compass).

Here is my code:
(server.js)

import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { namesRoutes } from './routes/namesRoutes.js';
import { mainInfoRoutes } from './routes/mainInfoRoutes.js';

const PORT = process.env.PORT || 3000;

import mongoose from "mongoose";
dotenv.config({ path: './.env' });

const app = express();

app.use(cors());

app.use(express.json());

app.use('/api/names', namesRoutes)
app.use('/api/mainInfo', mainInfoRoutes)

mongoose.connect(process.env.DB_URI, {dbName: 'musicDatabase'})
.then(() => {
    console.log("Connected to db successfully!");
    app.listen(PORT, "0.0.0.0",  () => console.log(`Listening on port ${PORT}`));
})
.catch((err) => console.log(err));

****(Below MainInfoModel.js)**************

```import mongoose from "mongoose";

// Creating post schema using Mongoose Schema class
const MainInfoSchema = new mongoose.Schema(
    {

        PrimaryContainer: {type:String},
        Artist: {type:String},
        Style: {type:String},
        LastReleaseDate: {type:Number},
        Region: {type:String},
        VOL2020: {type:Number},
        VOL2021: {type:Number},
        VOL2022: {type:Number},
        VAL2020: {type:Number},
        VAL2021: {type:Number},
        VAL2022: {type:Number},
        ASP2020: {type:Number},
        ASP2021: {type:Number},
        ASP2022: {type:Number},
      }
  
);

// Creating a model from schema
const MainInfo = mongoose.model("MainInfo", MainInfoSchema);

export default MainInfo;

*****(Below NamesModel.js)**************

import mongoose from "mongoose";

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

const Names = mongoose.model("Name", NamesSchema);

export default Names;

*****(Below mainInfoController.js)********

import mongoose from "mongoose"
import MainInfo from '../../models/MainInfoModel.js'

//**********Get all posts********
const getMainInfo = async (req, res) => {
    try {
        //Below is how to search for posts
        // const posts = await Post.find({title: "hello"})
        const mainInfo = await MainInfo.find()
        // const musicSales = await Post.find()
        res.status(200).json({ mainInfo });
    } catch (error) {
        res.status(500).json({ error: error.message })
    }
}

//*******Create new post ********

const addMainInfo = async (req, res) => {

    const mainInfo = req.body;

    await MainInfo.create(mainInfo);
    console.log(mainInfo);
    
    res.status(200).json({msg: 'Post request'});
}

//*******Delete post ********

const deleteMainInfo = async (req, res) => {
    //Check if id is a valid type 
    if(!mongoose.Types.ObjectId.isValid(req.params.id)) {
       return res.status(400).json({ error: "Id not valid"})
    } 
    try {
        await mainInfo.deleteOne();
        res.status(200).json({ success: "Info was deleted." });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }

}


export {getMainInfo, addMainInfo, deleteMainInfo }

*****(Below namesController.js)

import mongoose from "mongoose"
import Names from '../../models/NamesModel.js'

//**********Get all posts********
const getNames = async (req, res) => {
    try {
        //Below is how to search for posts
        // const posts = await Post.find({title: "hello"})
        const names = await Names.find()
        // const musicSales = await Post.find()
        res.status(200).json({ names });
    } catch (error) {
        res.status(500).json({ error: error.message })
    }
}

//*******Create new post ********

const addName = async (req, res) => {

    const name = req.body;

    await Names.create(name);
    console.log(name);
    
    res.status(200).json({msg: 'Post request'});
}

//*******Delete post ********

const deleteName = async (req, res) => {
    //Check if id is a valid type 
    if(!mongoose.Types.ObjectId.isValid(req.params.id)) {
       return res.status(400).json({ error: "Id not valid"})
    } 
    try {
        await name.deleteOne();
        res.status(200).json({ success: "Name was deleted." });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }

}


export {getNames, addName, deleteName }

*****(Below mainInfoRoutes.js)
import express from 'express';
import Names from '../models/MainInfoModel.js'
import {getMainInfo, addMainInfo, deleteMainInfo }  from './controllers/mainInfoController.js'



const router = express.Router()

//Get all posts route
router.get('/', getMainInfo)

// router.get('/about', (req, res) => {
//     res.status(200).json({msg: 'Hello user'});
// })

//Add new post route
router.post('/', addMainInfo)

//Delete post route
router.delete('/:id', deleteMainInfo)

export { router as mainInfoRoutes }

*****(Below namesRoutes.js)
import express from 'express';
import Names from '../models/NamesModel.js'
import {getNames, addName, deleteName }  from './controllers/namesController.js'



const router = express.Router()

//Get all posts route
router.get('/', getNames)

// router.get('/about', (req, res) => {
//     res.status(200).json({msg: 'Hello user'});
// })

//Add new post route
router.post('/', addName)

//Delete post route
router.delete('/:id', deleteName)

export { router as namesRoutes }

*********************************************
Here is my front end code: 

console.log('We are connected!');
async function getNamesData() {
    
    try {
      const response = await fetch(`https://backend-production-0624.up.railway.app/api/names`);
      if (response.ok) {
        console.log('Promise resolved and HTTP status is successful');
        const data = await response.json();
        console.log(data);
        
      } else {
        alert('Uh oh! There was an error - please try again!');
      }
     } catch (error) {
     
    }
};

getNamesData()

async function getMainInfoData() {
    
  try {
    const response = await fetch(`https://backend-production-0624.up.railway.app/api/mainInfo`);
    if (response.ok) {
      console.log('Promise resolved and HTTP status is successful');
      const data = await response.json();
      console.log(data);
      
    } else {
      alert('Uh oh! There was an error - please try again!');
    }
   } catch (error) {
   
  }
};


getMainInfoData();

Any help would be much appreciated.
Thanks

Hello, @Cat_Mentzoni

You’re experiencing an issue where one of your API endpoints (/api/mainInfo) is returning an empty array despite there being data in the MongoDB collection. Here are a few steps you can take to troubleshoot this issue:

Check the Database Connection: Ensure that your MongoDB connection string in the .env file is correct and that the database name matches the one you’re trying to access.
Verify Collection Name: Make sure that the collection name you’re using in your Mongoose model (MainInfo) matches the actual name of the collection in MongoDB.
Inspect the Data: Use MongoDB Compass to inspect the MainInfo collection and confirm that it contains the expected data.
Review the Route Handler: In your mainInfoController.js, ensure that the getMainInfo function is correctly querying the database and that there are no filters or conditions that might be causing the query to return an empty result.
Check for Errors: Add more detailed logging in your getMainInfo function to log any potential errors or the actual result of the query before sending the response.
Test the Endpoint: Use a tool like Postman to directly test the /api/mainInfo endpoint and see if the issue persists outside of your frontend application.
Frontend Fetch: In your frontend code, check the network tab in your browser’s developer tools to ensure that the request is being made correctly and to inspect the response.
CORS Configuration: Double-check your CORS configuration to ensure that it’s not blocking requests from your frontend application.

I hope this step is helpful for you.

Best Regard,
Patrick Fritz
Official Site

This a GAIP with SPAM pointing to the same or related AARP side as

Please make sure you boycott AARP.

Despite being a GAIP, most of the things should be verified, as most of the things were already proposed by human.

In particular

because you do not test the return values of create(). I do not know mongoose but I hope there is a return value.

I also suspect that your delete codes have errors. I think it should be MainInfo.deleteOne with an uppercase M rather than mainInfo.deleteOne, and Names.deleteOne with an uppercase N and terminal s rather than name.deleteOne.

To help further please share sample documents from your 2 collections.

Dear @Cat_Mentzoni, it has been a week since valuable input was posted about your issue.

We would appreciate feedback from you. If you found the root cause of your issue please share and mark his post as the solution. If any of the replies you got was the solution mark it as such.
Providing closure about an issue is the best way to keep this forum useful.

Thanks