Can't show data after API request, I use POSTMAN

How do i display data or did i fetch any data from API request?

  • client/
    • public/
    • src/
      • components/
      • pages/
    • package.json
    • package-lock.json
    • node_modules/
  • server/
    • config
      • config.js
    • controllers/
      • productController.js
    • models/
      • Product.js
    • routes/
      • productRoutes.js
    • index.js
    • db.js
    • package.json
    • package-lock.json
    • node_modules/
      -.env

at index.js

const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const mongoose = require('mongoose');

const Product = require('./models/Product');
const productRoutes = require('./routes/productRoutes');

dotenv.config();

const app = express();
const PORT = process.env.PORT;

app.use(cors());
app.use(express.json());

app.use('/api/products', productRoutes);

app.get('/', (req, res) => {
    res.send('Server is running');
});

// connectiion to db
const MONGO_URI = process.env.MONGO_URI;
mongoose.connect(MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    // useCreateIndex: true,
    // useFindAndModify: false
}).then(() => {
        console.log('index.js  MongoDB Atlast connected');

        app.listen(PORT, () => {    // listen to request only if already connected to db
            console.log(`index.js Server running on port ${PORT}`);
        });

        // Close the database connection when the Node.js process is exiting
        process.on('SIGINT', () => {
            mongoose.connection.close(() => {
                console.log('index.js Mongoose connection closed');
                process.exit(0);
            });
        });
    })
    .catch((err) => console.log(err));

at productRoutes.js

const express = require('express');
const router = express.Router();
const { getProducts } = require('../controllers/productController');
// GET /api/products
router.get('/', getProducts);
module.exports = router;

at productController.js

const Product = require('../models/Product');
const getProducts = async (req, res) => {
    try {
        const products = await Product.find({});
        console.log("products");
        res.json(products);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
}
module.exports = { getProducts };

just trying to test API.

I have collections in my db.

Hello @cashdomains, Welcome to the MongoDB community forum,

Make sure you are connected with the right database and fetching data from the right collection name in your model, can you show the model code?

I can help you with specific errors, but I can’t see any specific issues in your code, you have to debug your code by console.log step by step where is the exact issue.

I just want to test API and if it can fetch data but it seems it fetches nothing because POSTMAN only returns empty square brackets ( ). I know for sure that I’m connected to the database since atlast chart shows some data that was fetched. There is also a collection called “products” under cluster ecomm. I have no clue where did I miss.

here is my model but I think it has nothing to do since my atlast collection is inserted to database itself and not from vscode.

at models/Product.js

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    name: { type: String, required: true },
    description: { type: String, required: true },
    price: { type: Number, required: true },
    image: { type: String, required: true },
    countInStock: { type: Number, required: true },
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;

Thanks for the help anyways.

Hello @cashdomains,

If you understand JSON, it requires a key/property, here you are returning a whole array in JSON

instead, you need to respond in with a key/property,

res.json({ products: products });

I don’t see any other issues, otherwise, you need to debug yourself first as I have told you in a previous reply.

Thank you for answering @turivishal, I think I had found the problem. Can you teach me how to fix this?

at db.js

const mongoose = require("mongoose");
require('dotenv').config();

const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log(`Connected to MongoDB Atlas cluster: ${mongoose.connection.host}, database: ${mongoose.connection.db.databaseName}`);
    } catch (err) {
        console.log(err.message);
        process.exit(1);
    }

    mongoose.connection.on('disconnected', () => {
        console.log('Mongoose disconnected');
    });
    mongoose.connection.on('error', (err) => {
        console.log(`Mongoose connection error: ${err}`);
    });
};

module.exports = connectDB;

in console.log it tells that it is connected to test and not on ecomm. I dont know also where that test come from, i just inserted datas to test.products and it works. Here is the question now, how do i fetch ecomm.product instead of test.products?

@turivishal, i found the solution… thank you very much. I just need to specify the database name.

const mongoose = require("mongoose");
require('dotenv').config();

const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            dbName: 'ecomm' // specify the database name here
        });
        console.log(`Connected to MongoDB Atlas cluster: ${mongoose.connection.host}, database: ${mongoose.connection.db.databaseName}`);
    } catch (err) {
        console.log(err.message);
        process.exit(1);
    }

    mongoose.connection.on('disconnected', () => {
        console.log('Mongoose disconnected');
    });
    mongoose.connection.on('error', (err) => {
        console.log(`Mongoose connection error: ${err}`);
    });
};

module.exports = connectDB;
1 Like

Glad you solved your problem, Usually can pass the DB name in the connection string, like this

mongodb+srv://<username>:<password>@<host>/<db name>

And for local setup

mongodb://localhost:27017/<db name>

Refer to the reference doc,
MongoDB Connection String | Introduction | MongoDB | MongoDB.

4 Likes