Unable to access a property of an object using Mongoose

76 Views Asked by At

Sample data:

{
  "_id": "ObjectId_for_Site1",
  "name": "Site 1",
  "address": "123 Reeganangam",
  "manager": {
    "_id": "ObjectId_for_Manager1",
    "name": "Karthik",
    "type": "Manager"
  }
}

Controller

const getAllSites = async (req, res) => {
  try {
    const sites = await Site.find();
    console.log(sites);
    res.status(200).json(sites);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

Schema:

const managerSchema = new Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  type: String,
});

const siteSchema = new Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  address: String,
  manager: managerSchema,
});

const Site = mongoose.model('Site', siteSchema, 'Site_Collection');

Where controller is referenced:

router.get('/', async (req, res) => {
  try {
    const sites = await siteController.getAllSites();

    if (sites && Array.isArray(sites)) {
      const siteNames = sites.map((site) => site.name);
      res.render('main', {
        profile_picture_url: 'https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing',
        username: 'Sundar',
        sites: siteNames,
      });
    } else {
      res.status(500).json({ error: 'Failed to fetch sites data' });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Note: I encountered an issue while attempting to access a property of an object using Mongoose. While I could successfully retrieve a response via the URL http://localhost:3000/api/site, I encountered an error when trying to access http://localhost:3000/main. The error message received is as follows:

{"error":"Cannot read properties of undefined (reading 'status')"}

1

There are 1 best solutions below

5
Marya On

You're sending a response from the getAllSites controller, once you send a response the request-response cycle gets closed that's why the response.render() that is inside the router can't be processed

I've reorganised your code a little, please try out it and inform me if it worked out or not :

const getAllSites = async (req, res) => {
    try {
      const sites = await Site.find();
      if (sites && Array.isArray(sites)) {
        const siteNames = sites.map((site) => site.name);
        res.status(200).render('main', {
          profile_picture_url: '[https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing](https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing)',
          username: 'Sundar',
          sites: siteNames,
        });
      } 
      else {
        res.status(500).json({ error: 'Failed to fetch sites data' });
      }  
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  };

router.get('/', siteController.getAllSites);