I am learning Express with Mongoose and I am rendering a page where I run a forEach on a list of "campgrounds" from a MongoDB. My understanding is that when running the .find function it is optional to pass the err argument and run an if statement. But when I remove the err argument and the if statement altogether I get a "cannot run forEach on null while when I add it back (no other changes) my code runs smoothly. Not a problem when I add it back but I'm trying to understand what's going on in the background. Thanks in advance!
App.js code
//Create the camgrounds route
app.get("/campgrounds", function(req, res) {
//Get Campgrounds from DB
Campground.find({}, function(err, dbCampgrounds) {
//check for error
if (err) {
console.log(err);
//render the campgrounds page passing in the campground info from the db
} else {
res.render("campgrounds", {
renderCampGround: dbCampgrounds
});
}
});
});
And ejs file code
<div class="row">
<% renderCampGround.forEach(function(x){ %>
<div class="col-med-3 col-sm-6">
<div class="thumbnail">
<img src="<%= x.image %>">
</div>
<div class="caption">
<h4 <%= x.name %>>
</div>
</div>
</div>
<% }); %>
</div>
You are using the callback function so, all callbacks in the Mongoose use the pattern callback(err, data). So, if an error occurs while executing the query the error parameters will contain the error document and data will be null. If the query runs successfully then the error parameter will be null. But it is important to notice that not finding a document is not an error.
If you do not specify callback function then API will return the variable of type Query. Have a look.
So, if you don't want to use callback function then it will look like this.
//Create the camgrounds route
app.get("/campgrounds", function(req, res){
var campgrounds = Campgrounds.find({});
//execute a query at later time
campgrounds.exec(function (err, data) {
if (err) {
console.log(err)
}
else {
console.log(data)
}
}):
});
Related
I have a router which returns a specefic user's information based on the unique Object_id from MongoDB. This works fine, and I get the correct results, but they are returned on a "blank" page as a JSON object. I want to simply fetch the result and render them on my ejs page. Here are my route:
//Here are my router.js:
router.get('/user/get:id', function (req, res) {
MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
let dbo = db.db(DBName);
const query = {_id: objectId(req.params.id)}
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
res.send(resultTasks)
db.close();
});
});
});
//Here are my file.ejs:
<div class="card" v-for="post in filteredList">
<a v-bind:href="'/user/get' + post.id">{{ post.name }}</a>
</div>
Im still new so I know this is properly basic. I guess I have to change the res.send to something else, but now sure how.
You need to loop over resultTasks in your ejs template, something like:
<% resultTasks.forEach((post) => { %>
<div class="card" v-for="post in filteredList">
<a v-bind:href="/user/get/<%= post.id %>"><%= post.name %></a>
</div>
<%}); %>
Also, you probably need to change send in your endpoint with
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
db.close();
res.render('<path of your ejs file>', {
resultTasks: resultTasks, // pass data from the server to the view
});
});
I'm having an issue where my template is not rendering anything sent back from my mongodb database.
I have the following route and template:
// Removing items page
// --------------------------------------------------
router.post('/removeItems', (req, res) => {
res.render('removeItems', {prods: crudOps.getProducts(res)})
});
<form action="/admin/removeItems" method="POST">
<label for="item">ID</label>
<input type="text" class = "form-control" name = "id" is= "id" >
</form>
<div>
{{prods}}
</div>
<div class="container">
{{#each prods}}
<div class="form-group">
<form action="/admin/removeItems" method="POST">
<p>{{prods.name}}</p>
<img height='70px' width='70px'>{{prods.file}}</img>
<p>{{prods.value}}</p>
<p>{{prods.desc}}</p>
<p>{{prods._id}}</p>
<button class="btn btn-primary btn-sm" type="submit" class = "form-control">Remove</button>
</form>
</div>
{{/each}}
</div>
my function is exported from a file meant to handle crud operations
const getProducts = function(res){
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
if (err) {
throw err;
}
let db = client.db('account-app');
let products = db.collection('products');
let users = db.collection('users');
products.find().toArray(function(err, result) {
if (err) throw err;
console.log(result);
return result
})
client.close()
})
}
my assumption is that whatever is returned by my function can be used by my template inside the object passed to res.render. Am I perhaps missing some key for indexing? or am I mishandling my mongo call? I am able to console.log the data coming back.
all my documents inside my products collection have the following structure:
the file attribute is an image file.
name:"dd"
file:Binary('/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYICwgIyYn...', 0)
value:"dd"
desc:"dd
this is my first time using handlebars but everything looks fine to me, I'm not sure what's missing?
The add and update is happening on the same page, So initially all the input will be empty and when a data is click from the display page , all the data of the particular id should be displayed on all the inputs.
But when I'm trying to do that using ternary opeartor if condition , it doesn't seem to work.
EJS
<input
type="text"
class="form-control"
name="landingTitle"
value="<% result ? <%= result.landingTitle %> : '' %>" />
Backend
Node
// Initial Render
router.get("/", (req, res) => {
res.render("pages/dashboard");
});
//When the data is clicked for updation
router.get("/display/:id", (req, res) => {
MongoClient.connect(
process.env.ATLAS_URI,
{ useNewUrlParser: true },
(err, db) => {
if (err) throw err;
const dbo = db.db("xxx");
dbo
.collection("xxx")
.findOne({ _id: topic_id }, (err, result) => {
if (err) throw err;
res.render("pages/dashboard", {
result
});
db.close();
});
}
);
});
What am I doing wrong here ? Any advise will be appreciated , Thank you
I think you have a syntax issue here, please try the following and see if this works
value="<% if(result) { %> <%= result.landingTitle %> <% } else { %> '' <% } %>"
And if you are okay to use a non-inline version, you can always do the following
<%
var value = (result && result.landingTitle)? result.landingTitle : '';
%>
<input
type="text"
class="form-control"
name="landingTitle"
value="<%= value %>"
/>
There is one more simple and clean way. Check if result is defined using locals object inside the conditional operator.
<input
type="text"
class="form-control"
name="landingTitle"
value="<%= locals.result ? result.landingTitle : '' %>"
/>
It will work, whether you render the result object or not.
recently I faced the problem that the result from database is not as not be able to display on the page. What am I doing wrong ?
This is the function code which is located in index.js
res.locals.get_user_name = function () {
User.findOne({_id: 2}).exec().then(function (user) {
return user.name;
});
};
And this is a code template EJS
<div class="name"><% get_user_name() %></div>
I am exploring the use of the EJS templating system and am unsure of how to use it to get SQL data to be available to be rendered in a view.
In my app.js I have something like this:
conn.query("select name,age from people", function(err, people, moreResultSets) {
for (var i=0;i<people.length;i++){
console.log(people[i].NAME, "\t\t", people[i].AGE);
}
conn.close(function(){
console.log("Connection Closed");
});
});
And I have the following code to route the proper view:
app.get('/test1', function(req, res) {
res.render('pages/test1');
})
My confusion lies in making the people data available from the query
statement to be rendered in the view. All of the examples I have seen
have the variables defined locally inside the app.get code block and I
am unclear how to jump from that to my situation.
Thank you for any assistance you can provide!
-Andy
Render after you have the data.
app.get('/test1', function (req, res) {
conn.query("select name,age from people", function (err, people, moreResultSets) {
res.render('pages/test1', {
people: people
});
conn.close(function () {
console.log('Connection Closed');
});
});
});
HTML
<% if (people) { %>
<% for (var i = 0; i < people.length; i++) { %>
<div><%= people[i].name %></div>
<% } %>
<% } else { %>
<div>No people found</div>
<% } %>