sails.jsejssails-mongo

ReferenceError: " postIts.forEach(function(postit)" on list.ejs? postIts is not defined at eval (eval at compile


I need to loop through an object PostIts and display the "Id", " Title" with an ejs "forEach" Loop Am using sails.js "1.2.3" and mongodb on local host, but i get error

ReferenceError : postIts is not defined at eval (eval at compile ?

Here is the code on the PostItsController.js:

module.exports = {

    list: function(req, res) {
        // res.view('list');
        PostIts.find({}).exec(function(err, postIts) {
            if (err) {
                res.send(500, { error: 'Database Error' });
            }
            res.view('list', { postIts: postIts });
        });
    }
};

And here is the code on list.ejs:

     <tbody>
       <% postIts.forEach(function(postit){ %>
            <tr>
                <td>
                    <%= postit.id %>
                </td>
                <td>
                    <%= postit.title %>
                </td>
                <td></td>
            </tr>
            <% }) %>
       </tbody>

I should get the value of the ID and title displayed on the list.ejs page in a table, but instead I get an error that the postIts object is not defined.


Solution

  • First of all your route '/postIts/list': { view: 'list' }, should point to an action (since it has backend logic) not a view, so in your case "/postIts/list": "PostItsController.list", but if you're using actions2 things would be simpler

    Secondly you don't need to tell your users that you have a database error error: "Database Error"

    Using Actions2

    sails generate action post/list
    

    In your config/route.js

     'POST /api/v1/post/list': { action: 'post/list' },
    

    In your action

    module.exports = {
      friendlyName: "List Posts",
    
      description: "List all post in our site",
    
      inputs: {},
    
      exits: {
        success: {
          description: "The path to your template file",
          viewTemplatePath: "list"
        }
      },
    
      fn: async function(inputs) {
        var posts = await Post.find();
        // All done.
        return { postIts: posts };
      }
    };
    
    

    postit works

    An Boohoo! it works https://sailsjs.com/documentation/concepts/actions-and-controllers/routing-to-actions