i have to run the npm command npm install express mongoose cors
then i am running database called studentsRecords with collection student having the following data
db.students.insertMany({id:1},{name:’John’},{id:2,name:’Doe’});
i want to display those data to my web browser with express only as i did on the code bellow , but it display errors (i.e does not fetch any of the given data from database) , how to fix the code so it can work properly?
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Schema and model
const Schema = mongoose.Schema;
const DataSchema = new Schema({
name: String
});
const Data = mongoose.model('Data', DataSchema);
// Route to fetch data by name and id
app.get('/data/', async (req, res) => {
try {
const { name } = req.params;
const data = await Data.find({ name: name }, { _id: 0, name: 1 });
if (!data || data.length === 0) {
return res.status(404).send('Data not found');
}
res.json(data);
} catch (err) {
console.error('Failed to fetch data', err);
res.status(500).send('Internal Server Error');
}
});
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
2
Answers
In principle your code is well-set.
I tried the same, and it resulted in the desired output below. The subsequent post explains a few corrections to be applied to make your code completely working. Please try it and for clarifications if any required from me, please post your comments.
Testing in Browser:
Enclosing a few observations and comments:
point 1:
“…then i am running database called studentsRecords with collection student having the following data
db.students.insertMany({id:1},{name:’John’},{id:2,name:’Doe’});…”
observations & comments:
As per the above note,
Now we shall create the documents as below:
The prior requirements are the db should be pointing to the database studentsRecords and the insertMany statement should refer to the collection students. The respective codes are given below.
point 2:
// MongoDB connection
mongoose.connect(‘mongodb://localhost:27017/mydatabase’, { useNewUrlParser: true, useUnifiedTopology: true });
comments:
The database referenced in the connection string is to be corrected as per the discussions we have done in point 1. Therefore the corrected statement would be as below. Please note that the two keys useNewUrlParser and useUnifiedTopology passed into the options object are now deprecated therefore it is now omitted.
point 3:
…
const Data = mongoose.model(‘Data’, DataSchema);
…
comments:
The collection name passed into the method model needs to be changed from Data to student, this is again as per the discussion we have done in point 1. Please also note that it must be a singular name, therefore it is student not students. Mongoose will automatically look for its plural name. The corrected code is given below:
point 4:
// Route to fetch data by name and id
app.get(‘/data/’, async (req, res) => {
comments:
The route path /data/ should be prefixed with a route parameter as well. This is to get the respective value specified in the request URL. The corrected code is given below.
The full listing of corrected code:
Version 2 of the code: A new route path for all is added.