skip to Main Content

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


  1. 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:

    Request URL : http://localhost:3000/data/John
    
    Response : 
    [
      {
        "name": "John"
      }
    ]
    

    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,

    database name : studentsRecords
    collection name : students // Please note it is not just student alone, s is also suffixed.
    

    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.

    // start mongo shell
    command prompt>mongosh
    
    // check the list of available databases 
    mongosh prompt>show dbs
    
    // switch to the database studentsRecords
    mongosh prompt>use studentsRecords
    
    // create the documents, please note there should be a set of curly braces to separate each document.
    mongosh prompt>db.students.insertMany({id:1,name:'John'},{id:2,name:'Doe'});
    
    // check and verify the documents are created as desired
    mongosh prompt>db.students.find();
    [
      { _id: ObjectId('6672396e2241632216628d55'), id: 1, name: 'John' },
      { _id: ObjectId('6672396e2241632216628d56'), id: 2, name: 'Doe' }
    ]
    

    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.

    …
    mongoose.connect('mongodb://localhost:27017/studentsRecords);
    …
    

    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:

    const Data = mongoose.model(student, DataSchema);
    

    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.

    …
    app.get('/data/:name’, async (req, res) => {...
    

    The full listing of corrected code:

    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/studentsRecords');
    
    // Schema and model
    const Schema = mongoose.Schema;
    const DataSchema = new Schema({
      name: String,
    });
    
    const Data = mongoose.model('student', DataSchema);
    
    // Route to fetch data by name and id
    app.get('/data/:name', 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}/`);
    });
    
    Login or Signup to reply.
  2. Version 2 of the code: A new route path for all is added.

    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/test');
    
    // Schema and model
    const Schema = mongoose.Schema;
    const DataSchema = new Schema({
      name: String,
    });
    const Data = mongoose.model('student', DataSchema);
    
    // Route to fetch all
    // IMPORTANT : keep this route path always on top of the other route path '/data/:name'
    // else retrieval will fail.
    app.get('/data/all', async (req, res) => {
      try {
        const data = await Data.find({}, { _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');
      }
    });
    
    // Route to fetch data by name and id
    app.get('/data/:name', 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}/`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search