Fetch data brings blank array, even it has data. I'm using atlas with mern

20 Views Asked by At

`//server.js

const express = require('express');
const cors = require("cors");
const { MongoClient } = require('mongodb');
const conn = require('./db');
const bookModel = require('./models/models');
const routes = require('./routes/routes');
const app = express();
const PORT = process.env.PORT || 3000;
const mongoUri = "mongodb+srv://jaydeepdbendre:[email protected]/?retryWrites=true&w=majority";
const dbName = 'MBDB';
const collectionName = 'MBDB';
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(cors({ origin: \["http://localhost:5173"\] }));
app.use('/books', routes);

const connectAndFetchData = async () =\> {
const client = new MongoClient(mongoUri);

try {
await client.connect();
console.log('Connected to the Atlas');

const db = client.db(dbName);
const collection = db.collection(collectionName);

const data = await collection.find({}).toArray();
console.log('Fetched data:', data); // Log the fetched data

return data;

} catch (error) {
console.error('Error:', error);
throw error;
} finally {
await client.close();
}
};
const handleServerError = (res, error) =\> {
console.error('Error:', error);
if (res) {
res.status(500).send('Internal Server Error');
}
};

app.get("/", async (req, res) =\> {
try {
const data = await bookModel.find().exec();
res.status(200).json(data);
} catch (error) {
handleServerError(res, error);
}
});

app.listen(PORT, () =\> {
console.log(`Server is running on port ${PORT}`);
});

conn.on("connected", () =\> {
connectAndFetchData(null).catch(err =\> handleServerError(null, err));
});\`

//BookCard

import { useEffect, useState } from "react";
import "./BookCard.css"; // Assuming you have styles for BookCard
import axios from "axios";

const BookCard = () =\> {
const \[bookData, setBookData\] = useState(\[\]);

useEffect(() =\> {
axios
.get("http://localhost:3000/") // Adjust the URL based on your server
.then((res) =\> {
console.log("Response from API:", res.data);
setBookData(res.data);
})
.catch((error) =\> {
console.error("Error fetching data:", error);
});
}, \[\]);

return (
\<div className="bookCardList"\>
{bookData.length \> 0 ? (
bookData.map((book) =\> (
\<div key={book.\_id} className="bookCard"\>

<p>Author (English): {book\["Author Name (English)"\]}</p>
<p>Author (Marathi): {book\["Author Name (Marathi)"\]}</p>
<p>Title (English): {book\["Title (English)"\]}</p>
<p>Title (Marathi): {book\["Title (Marathi)"\]}</p>
<p>Pages: {book.Pages}</p>
<p>Genres: {book.Genres}</p>
<p>Year: {book.Year}</p>
\
))
) : (
<h4>No books found</h4>
)}
\
);
};

export default BookCard;
\[nodemon\] starting `node server.js`
Server is running on port 3000
Connected to the Atlas
Fetched data: \[
{
\_id: new ObjectId("6512f65321afc2532dc3c7f0"),  
'Author Name (English)': 'Narayan Dharap',
'Author Name (Marathi)': 'नारायण धारप',
'Translator (English)': '',
'Translator (Marathi)': '',
'Title (English)': 'Shapath',
'Title (Marathi)': 'शपथ',
'Img URL': 'https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1517938268i/38389590.jpg',
'Literature Type (English)': 'Novel',
'Literature Type (Marathi)': 'कादंबरी',
Pages: '249',
Year: '2018',
Genres: 'Horror',
'Release Date': '12 January, 2018',
'Publisher (English)': 'Saket Prakashan',
'Publisher (Marathi)': 'साकेत प्रकाशन'
},
{
\_id: new ObjectId("6512f65321afc2532dc3c7f1"),  
'Author Name (English)': 'P.L. Deshpande',
'Author Name (Marathi)': 'पु.ल. देशपांडे',
'Translator (English)': '',
'Translator (Marathi)': '',
'Title (English)': 'Vyakti Aani Vyalli ',
'Title (Marathi)': 'व्यक्ती आणि वल्ली',
'Img URL': 'https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1322727434i/11553117.jpg',
'Literature Type (English)': 'Short Stories',
'Literature Type (Marathi)': 'कथा संग्रह ',
Pages: '202',
Year: '1966',
Genres: 'Humour',
'Release Date': '1 January, 1966',
'Publisher (English)': 'Mauj Prakashan',
'Publisher (Marathi)': 'मौज प्रकाशन'
}
\]
Connected to the Atlas
Fetched data: \[
{
\_id: new ObjectId("6512f65321afc2532dc3c7f0"),  
'Author Name (English)': 'Narayan Dharap',
'Author Name (Marathi)': 'नारायण धारप',
'Translator (English)': '',
'Translator (Marathi)': '',
'Title (English)': 'Shapath',
'Title (Marathi)': 'शपथ',
'Img URL': 'https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1517938268i/38389590.jpg',
'Literature Type (English)': 'Novel',
'Literature Type (Marathi)': 'कादंबरी',
Pages: '249',
Year: '2018',
Genres: 'Horror',
'Release Date': '12 January, 2018',
'Publisher (English)': 'Saket Prakashan',
'Publisher (Marathi)': 'साकेत प्रकाशन'
},
{
\_id: new ObjectId("6512f65321afc2532dc3c7f1"),  
'Author Name (English)': 'P.L. Deshpande',
'Author Name (Marathi)': 'पु.ल. देशपांडे',
'Translator (English)': '',
'Translator (Marathi)': '',
'Title (English)': 'Vyakti Aani Vyalli ',
'Title (Marathi)': 'व्यक्ती आणि वल्ली',
'Img URL': 'https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1322727434i/11553117.jpg',
'Literature Type (English)': 'Short Stories',
'Literature Type (Marathi)': 'कथा संग्रह ',
Pages: '202',
Year: '1966',
Genres: 'Humour',
'Release Date': '1 January, 1966',
'Publisher (English)': 'Mauj Prakashan',
'Publisher (Marathi)': 'मौज प्रकाशन'
}
\]

on localhost 5173
i got No books found

I need to get data to display on webpage or atleast on console, it shows blank array.

I have used chatgpt and bard to find the error but they were not useful.

As you can see, I've added what appears on terminal. It shows server is running, atlas is connected and also show the data from atlas.
but in frontend it shows blank array.

0

There are 0 best solutions below