【发布时间】:2019-01-05 19:05:51
【问题描述】:
我的 forEach 循环在尝试从数据库 (mongodb) 获取数据时无法在 ejs 文件中工作,它包含一个名为 campground 的集合。但是当我将对象集合存储在 myapp.js 代码中的数组中时,它可以正常工作。但是当我尝试通过在数据库中存储数据来实现时,它会显示错误 campground.forEach is not a function
这是我的代码:
myapp.js
var express=require("express");
var app=express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/campit");
var campgroundSchema=new mongoose.Schema({
name:String,
image:String
});
var campground=mongoose.model("campground",campgroundSchema);
app.get("/create",function(req,res){
campground.find({},function(err,campgrounnd){
if(err){
console.log(err);
}
else{
res.render("index.ejs",{campground:campground});
}
})
});
app.listen("3000",function(){
console.log("listening from server 3000");
});
index.ejs 文件,它应该被渲染并且它包含那个 for.Each 循环
<div class="container">
<div class="row no-gutters">
<% campground.forEach(function(camp){ %>
<div class="col col-lg-4 img-thumbnail">
<img class="but" height="75%" width="100%" src="<%=camp.image%>" alt="image">
<div class="text-center">
<h6><%= camp.name %> </h6>
<button class="btn btn-outline-info " type="button" name="more info"> more info</button>
</div>
</div>
<% }); %>
</div>
</div>
任何帮助都将受到高度评价..谢谢 console.log the campground
【问题讨论】:
-
您能否添加您遇到的错误
-
请看问题的开头
-
将这一行 console.log(campground) 放在 res.render("index.ejs",{campground:campground}); 之前,看看打印了什么。
-
它显示了很多我不知道从哪里来的 json 数据,我应该发布它的图像吗??
-
请张贴我认为您在 campgrounnd 中获得了 mongoDB 光标。