skip to Main Content

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](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 : Cannot able to access property of an object using mongoose. I was able get response with http:localhost:3000/api/site but not with http:localhost:3000/main.Instead I get this error :
{"error":"Cannot read properties of undefined (reading ‘status’)"}

2

Answers


  1. I’m not sure of my answer because I can’t run the code.
    but as I can see, you’ve already responded to the coming request inside getAllSites controller.
    once you send a response the request-response cycle gets closed, therefore this line of code :

    const sites = await siteController.getAllSites();
    

    doesn’t get the sites value that it expected and waited for because getAllSites does close the request-response cycle, it doesn’t return any value.

    I think you should reorganise your code.
    I can’t see any point in creating a whole controller just to do this line:
    const sites = await Site.find();
    you may consider doing it like this: (in my opinion it’s more cleaner)

    router.get('/', getAllSites);
    

    then move all the code to be inside getAllSites and at the end, send the response from there just like you did.

    or modify your controller to be like this :

    const getAllSites = async (req, _, next) => {
    try {
    const sites = await Site.find();
    req.sites = sites; // this is going to include the data to the current request so the next middleware in the stack can access it.
    next();
    }
    } catch (error) {
    res.status(500).json({ error: error.message });
    }
    });
    
    
    router.get('/', getAllSites, async (req, res) => {
    try {
    const sites = req.sites;
    
        if (sites && Array.isArray(sites)) {
          res.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 });
    }
    });
    

    I hope my answer can be some kind of help to you and others

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search