【问题标题】:In javascript I have passed the object to ejs file, but it still says that object is null在javascript中,我已将对象传递给ejs文件,但它仍然说对象为空
【发布时间】:2020-04-25 12:41:02
【问题描述】:

这是 Colt Steele 的 yelp camp 项目。我一直在创建 cmets,我总是收到此警告 Cannot read property 'name' of null。 这是我的 app.js 文件

app.get('/campgrounds/:id', function(req, res){
// 	find campground with the provided ID
	Campground.findById(req.params.id).populate('comments').exec(function(err, foundCampground){
		if(err){
			console.log(err);
		} else {
			console.log(foundCampground)
			res.render('show', {campground: foundCampground});
		}
	});
});

这是 show.ejs 文件

<%- include('partials/header') %>
<h1>
    <%= campground.name %>
</h1>
<img src='<%= campground.image %>'>
<p><%= campground.description %></p>

<% campground.comments.forEach(function(comment){ %>
    <p><%= comment.author %> - <%= comment.text %></p>
<% })%>
<%- include('partials/footer') %>

有人可以帮我看看我的代码有什么问题吗?如果我签入数据库,露营地已经有数据了

【问题讨论】:

  • console.log(foundCampground) 的结果是什么?
  • foundCampground 的输出是什么?
  • 它说它是未定义的
  • 露营地是在同一个文件夹中还是在名为 campgrounds 的子文件夹中?

标签: javascript node.js mongodb associations ejs


【解决方案1】:

您的 campground.cmets json 数据可能存在问题。

const foundCampground = {
            name : 'test',
            description:'desc test',
            image : 'test.jpg',
            comments: [
                {
                    author:"product1",
                    text : "text1"
                },
                {
                    author:"product2",
                    text : "text2"
                }
            ]
        }
res.render('show',{campground:foundCampground})

尝试使用这个静态 json,如果它工作正常,然后检查来自数据库的 json 数据。如果您遇到与数据相关的问题,请始终尝试使用静态数据

【讨论】:

    【解决方案2】:

    我也遇到了同样的问题。就我而言,我从名为“campground”的集合中删除了所有 cmets。请检查您的数据库中的 cmets。如果您使用的是 mongodb,您可以这样做, ```

    show dbs
    use yelp_camp // name of your db
    show collections
    

    (您可能会注意到您的“露营地”收藏为空) 现在刷新您的网页,您会注意到您的“/campgrounds/”网页没有任何露营地,因此使露营地对象 == null。

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 2020-04-26
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2016-07-03
      相关资源
      最近更新 更多