Can anyone can help me to display the data in my backend server
It shows only {“data”:}, But my collection having some data int it
Can anyone can help me to display the data in my backend server
Please do not post your code as an image. We cannot cut-n-paste it.
Are you using mongoose? If not, then find() returns a cursor. You have to consume the cursor. Calling toArray() is one way to do it.
Server.js
const express = require(“express”);
const bodyParser = require(“body-parser”);
const cors = require(“cors”);
const db = require(’./db’);
const app = express();
const productRouter = require(’./routes/productRouter.js’)
var corsOptions = {
origin:"http://localhost:3000"
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
db.on(‘error’, console.error.bind(console, ‘MongoDB Connection Failed:’))
app.get("/",(req,res)=>{
res.json({message: "Welcome to E-canteen"});
});
const PORT = process.env.PORT || 6505;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.use(’/api/’,productRouter)
productRouter.js
const express = require(‘express’)
const router = express.Router()
const Product = require(’…/models/productModel’)
router.get(’/’, async (req, res) => {
try {
const products = await Product.find([])
res.status(200).send({data:products})
} catch (err) {
res.status(400).send({ error: err})
}
})
router.get(’/products-by-categories’, async (req,res) =>{
try {
const products = await Product.aggregate([
{ $match: {}},
{ $group: {
_id: '$category',
products: {$push: '$$ROOT'}
}},
{$project: { name: '$_id',products: 1, _id: 0}}
])
res.status(200).send({data: products})
} catch (err) {
res.status(400).send({error: err})
}
})
module.exports = router;
Why did you added the empty array parameter to find()
where you simply had
const products = await Product.find()
Your code does not show how you connect to your database server. It is probably done in
So
Have you tried
Share a screenshot that shows the data you have in your database. The ideal is a screenshot using mongosh so we can see the database and the collection use.