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
});
});
Related
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)
}
}):
});
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.
I am learning how to display mongodb data in html, but the code cannot work when I learn from network. I want to create the button to change the page to view data, and I don't know how to render data to ejs.
I try to find some method to solve the problem in network, but most of them are not the problem which I get.
code of find data
app.post('/viewdata', function (req, res) {
res.render('staffDisplay');
try{
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
}else{
var game=[];
var collection = client.db("GameDB").collection("Game");
var result = collection.find();
result.forEach(function(error,result){
if(error){
console.log(error);
}else{
if(result != null){
game.push(result);
}else{
console.log(game);
res.render('views/staffDisplay.ejs',{game:result})
}
}
})
console.log('show');
client.close();
}
});
}catch(ex){
throw new Error(ex.toString());
}
});
display.ejs
//skip the html code
<ul>
<% for(var i=0;i<=game.length;i++) {%>
<li><%=game[i].gName%></li>
<li><%=game[i].gDesc%></li>
<li><%=game[i].gDate%></li>
<%}%>
</ul>
the result is display 'game is not define', how can I do?
Can you try to remove this res.render('staffDisplay'); on the first part then replace res.render('views/staffDisplay.ejs',{game:result}) with this res.render('staffDisplay.ejs',{game:result})
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>
My index.js file get method
app.get('/getdata', function(req, res){
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('satyamsoft').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
console.log(resultArray);
});
});
res.render('pages/getdata', {holedata: resultArray});
});
My getdata.ejs file
<h2> Family Details </h2>
<ul>
<% holedata.forEach(function(data) { %>
<li><%= data.name %> - <%= data.title %> - <%= data.age %></li>
<% }); %>
</ul>
After executing the get method in the console showing data which is fetch from mongodbColnose data
But in the web page showing empty enter image description here
Am i doing anything wrong. Please help me. Advance thanks.
This might help on client side in your .ejs file -
<script>
var holedata = <%- JSON.stringify(holedata) %>;
</script>