帆,在forEach循环中没有定义EJS数据。

问题描述 投票:1回答:1

我正在根据@bradtraversy的教程用MongoDB开发Sails.js CRUD应用程序(文章管理)。当我试图使用EJS语法和forEach循环从数据库中显示文章时遇到了问题。错误提示 "articles data is not defined"。错误图片

基本上我是通过Sails把考试记录传给Mongo的。/Create?title=ArticleOne%20body=BodyOne URL蓝图。在Mongo中可以清晰地看到文章。MongoDB文章图片

datastores.js是为Mongo配置的。

 module.exports.datastores = {

 mongodb: {

    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    database: 'articlebase'
  },

};

routes.js点出了list.ejs视图。

 module.exports.routes = {

  '/': { view: 'pages/homepage' },
  '/articles/list': { view: 'pages/list' },
  '/articles/add': { view: 'pages/add' },

};

Article.js模型。

module.exports = {

  attributes: {
     title:{
       type: 'string'
     },
     body:{
      type: 'string'
    }
  },
  datastore: 'mongodb'

};

ArticlesController.js

module.exports = {

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

        });
    },

    add: function(req, res){
        res.view('add');
    }

};

最后麻烦的是list.ejs视图。

<h1 class="display-4">Articles</h1>
<table class="table table-striped">
    <thead>
        <tr>
            <th>#</th>
            <th>Title</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <% articles.forEach(function(article){ %>
            <tr>
                <td><%= article.id %></td>
                <td><%= article.title %></td>
                <td>
                    <a href="/articles/edit/<%= article.id %>" class="btn btn-primary">Edit</a>
                    <form class="d-inline" action="/articles/delete/<%= article.id %>" method="post">
                        <input type="submit" value="Delete" class="btn btn-danger">
                    </form>
                </td>
            </tr>
        <% }); %>
    </tbody> 
</table>

如何用EJS正确显示MongoDB "文章 "集合中的文章?先谢谢你的帮助

mongodb express sails.js ejs sails-mongo
1个回答
0
投票

我怀疑你的控制器方法遇到了错误,但你在得到错误时没有返回。我的第一个猜测是 文章文章 但我可能是错的。改成这样,帮助你看清事情的真相。

list:function(req, res){
    Articles.find({}).exec(function(err, articles){
        if(err){
            sails.log('Error summary: ' + err);
            sails.log(err);
            return res.send(500, {error: 'Database Error'}); // note the return!
        }
        res.view('list', {articles:articles});
    });
},

否则,错误追踪做得很好!

© www.soinside.com 2019 - 2024. All rights reserved.