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