The error you’re encountering, Cannot read properties of undefined (reading ‘sort’) in your PUG template, suggests that the authors variable is not being passed into the template or is undefined at the time the template is being rendered.
Here are some steps to troubleshoot and fix this issue:
Check the Route Handler:
Ensure that in the route handler in your Express.js code, you are passing the authors variable to the template. It should look something like this:
In this snippet, authorsArray should be the array of author objects that you want to display in the template.
Ensure authors is an Array:
The authors variable needs to be an array for the sort function to work. If it’s not an array, you’ll encounter the error you’re seeing. Make sure that the data you’re passing to the template is indeed an array.
Check for Null or Undefined:
It’s good practice to check if authors is null or undefined before trying to access its properties or methods. You could modify your PUG template to include a check like this:
if typeof authors !== 'undefined' && authors
- authors.sort(function(a, b) { ... });
for author in authors
...
else
p No authors available
This will render a message if no authors are available instead of causing an error.
Review Data Passed to the Template:
Double-check the data being passed to the PUG template from your Node.js/Express.js server. Make sure that the authors data is correctly retrieved from the database and passed to the PUG renderer.
Debugging:
If you’re still having trouble, add console.log(authorsArray) in your route handler before the res.render call to see what data is being passed to the PUG template.