Reputation: 61
My forEach loop is not working in ejs file while trying to fetch data from data base (mongodb) it contain a collection namely campground.but it work fine when I stored a collection of object in a array in myapp.js code.but when i m trying to implement through storing data in database it shows a error of campground.forEach is not a function
Here is my code:
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 file which is suppose to render and it contain that for.Each loop
<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>
any help will be highly appriciated..thank you console.log the campground
Upvotes: 2
Views: 1243
Reputation: 864
The find method in MongooseJS returns a Query object (reference). There are a few ways you can do searches and return results.
campground.find().exec(function(err,result){
if(err){
console.log(err);
}
else{
res.render("index.ejs",{campground:result});
}
});
Upvotes: 3
Reputation: 2907
I think you are conflicting variable name
var campground=mongoose.model("campground",campgroundSchema); // here is a campground
app.get("/create",function(req,res){
campground.find({},function(err,result /* <-- */){ // the result is also campgrounnd
if(err){
console.log(err);
}
else{
res.render("index.ejs",{campground:result/* <-- */}); // pass result instead campgrounnd
}
})
});
Upvotes: 0