I'm trying to do "Orders page" that has a list of orders in a single page, but it should have seperate sections. One is for "Already made" and the other is for "Pending". It has a simple database with a field "isDone" that is either true or false. So as I imagine, if it is true, then it should appear on "Already made" section, but the problem is, that if statment doesn't work for some reason in .ejs.
<body class="container">
<main>
<div class="jumbotron">
<h1>Pending</h1>
</div>
<% orders_list.forEach(function(order){ %>
<% if(order.isDone == false) { %>
<div>
<h3><a href='<%= order.url %>'><%= order.name %></a> - <%= order.price %> euru</h3>
<hr>
</div>
<% } %>
<% }) %>
<div class="jumbotron">
<h1>Already made</h1>
</div>
<% orders_list.forEach(function(order){ %>
<% if(order.isDone == true) { %>
<div>
<h3><a href='<%= order.url %>'><%= order.name %></a> - <%= order.price %> euru</h3>
<hr>
</div>
<% } %>
<% }) %>
</main>
</body>
var express = require('express');
var router = express.Router();
var Order = require('../models/order');
router.get('/orders', function(req, res){
Order.find({})
.exec(function(err, list_orders){
if (err) {return next(err)};
// If Successful
res.render('../views/pages/index', {orders_list : list_orders});
});
});
module.exports = router;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var OrderSchema = new Schema(
{
isDone: {type: Boolean, required: true},
name: {type: String, required: true},
quantity: {type: Number, required: true},
price: {type: Number, required: true},
phone: {type: Number},
});
OrderSchema
.virtual('url')
.get(function(){
return '/order/' + this._id;
});
module.exports = mongoose.model ('Order', OrderSchema);
I expect 'isDone' == true orders to go to 'Already made' section, and 'isDone' == false orders should go to the 'Pending' section. But not even single item appears. Database is connected successfully, if there are no if statments then orders appear on the page.
In your if condition you have quote your true value because ejs file is taking it as a value instead of a boolean value , so quote your true like this and it will work fine.
<% if(orders_list[i].isDone == 'true'){ %>
<div>
<h3><a href='<%= orders_list[i].url %>'><%= orders_list[i].name %></a> - <%= orders_list[i].price %> euru</h3>
<hr>
</div>
<% } %>
Related
I created a schema for the supports tickets I have to show on this view but, they are not actually showing. The data is showing in the console so I don't really understand the problem.
const mongosee = require ('mongoose');
const {Schema} = mongosee;
const AssignedTicketSchema = new Schema ({
name: { type: String, required: true},
pnumber: { type: String, required: true},
problem: { type: String, required: true},
support: {type: String, required: true},
date: { type: Date, default: Date.now}
});
module.exports = mongosee.model('AssignedTicket', AssignedTicketSchema)
These are the routes
router.post('/tickets/assign-tickets', isAuthenticated, async (req, res) => {
const {name, pnumber, problem, support}= req.body;
const newAssignedTicket = new AssignedTicket({name, pnumber, problem, support})
newAssignedTicket.user = req.user.id;
await newAssignedTicket.save();
req.flash('success_msg', 'Ticket assigned succesfully')
res.redirect('/tickets/assigned-tickets');
});
router.get('/assigned-tickets', isAuthenticated, async (req, res) => {
const assignedtickets = await AssignedTicket.find({user: req.user.id}).lean().sort({date: 'desc'});
res.render('tickets/assigned-tickets', {assignedtickets} );
});
And this is the view
<div class="row">
{{#each assignedtickets}}
<div class="col-md-3">
<div class="card">
<div class="card-body">
<h4 class="card-name d-flex justify-content-between align-items-center">
{{name}}
</h4>
<p>{{pnumber}}</p>
<p>{{problem}}</p>
<p>{{support}}</p>
</div>
</div>
</div>
{{else}}
<div class="card mx-auto">
<div class="card-body">
<p class="lead">There are no support tickets yet.</p>
Create a new support ticket
</div>
</div>
{{/each}}
</div>
From this line
res.redirect('/tickets/assigned-tickets');
Are you expecting to redirect to this method?
router.get('/assigned-tickets', isAuthenticated, async (req, res) => {
const assignedtickets = await AssignedTicket.find({user: req.user.id}).lean().sort({date: 'desc'});
res.render('tickets/assigned-tickets', {assignedtickets} );
});
Seems like the path is not an exact match.
Also, the redirect seems like is not sending the user id, probably you can send it as a parameter?
Check this other answers How do I redirect in expressjs while passing some context?
Express.js: Is it possible to pass an object to a redirect like it is with res.render?
how to pass data and redirect in express
I have tried almost all the solutions but couldn't get this fixed.
I'm trying to get multiple collection of data (Mongodb Atlas) onto one ejs file. But I can't get data onto the rendered ejs sheet. But when I tested with locus I can see all the data received from the database up to res.render("/vendor/show"). But it is not passing onto ejs template.
I have three sets of data sitting on the mongo Atlas:
const vendorSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
});
const newpromoSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
vendor:String,
description:String,
sdate:String,
edate:String,
});
const neweventSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
description:String,
vendor:String,
sdate:String,
edate:String,
});
router.get("/vendors/:id",function(req,res) {
var events={}; //Create Empty event Object
var promotions={}; //Create Empty promotion Object
var vendors={};//Create Empty vendor Objext
Promotion.find({},function (err,allPromotions) {
if (err) {
console.log(err);
} else {
//Find Collection And Assign It To Object
promotions=allPromotions;
}
});
Event.find({},function(err, allEvents) {
if (err) {
console.log(err);
} else {
events=allEvents;
}
});
Vendor.find({},function(err,allVendors){
if(err){
console.log(err);
}else{
vendors=allVendors;
//find order collection and passing it to ejs templates
res.render("vendors/show",{ event:events, promotion:promotions vendor:vendors});
}
});
});
Show.ejs code as
<%=vendor.name%>
<%=promotion.name%>
<%=event.name%>
You need to handle the async process. In your current code, there are three async processes. Please go through following the link you will definitely get an idea about it.
https://blog.risingstack.com/mastering-async-await-in-nodejs/
if you need more help Don’t hesitate to comment.
I managed to get all data using the below function. But now I have another issue, need to filter all the Promotions and Events by vendor But it doesn't filter.
Data Schema
const neweventSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
description:String,
vendor:String,
sdate:String,
edate:String,
});
const Event = mongoose.model("Event",neweventSchema);
module.exports = Event;
//SCHEMA SETUP===============================================================================================================
const newpromoSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
vendor:String,
description:String,
sdate:String,
edate:String,
});
//compile into a model
const Promotion = mongoose.model('Promotion',newpromoSchema);
module.exports = Promotion;
//SCHEMA SETUP===============================================================================================================
const vendorSchema = new mongoose.Schema({
name:String,
image:String,
imageId:String,
});
const Vendor = mongoose.model("Vendor", vendorSchema);
module.exports = Vendor;
Routes as below
router.get("/vendors/:id", function (req, res) {
Vendor.find({}, function (err, allVendors) {
if (err) {
console.log(err);
} else {
// //Find Collection And Assign It To Object
Event.find({}, function (err, allEvents) {
if (err) {
console.log(err);
} else {
Promotion.find({}, function (err, allPromotions) {
if (err) {
console.log(err);
} else {
//find order collection and passing it to ejs templates
res.render("vendors/show", {event: allEvents, promo: allPromotions, vendor: allVendors});
}
});
}
});
}
});
});
EJS Show page But It doesn't get filtered.
<!-- Trying to filter all the events by vendor if event's vendor name == vendor name then show on the show page -->
<%if(event.vendor === vendor.name){%>
<div class = "container-fluid">
<div class = "row">
<%event.forEach(function(events){%>
<div class="col-sm-6 col col-md-4 col-lg-3">
<div class="thumbnail">
<img src ="</%=events.image%>" class="rounded" width="304" height="236">
<div class="caption">
<h4><%=events.name%></h4>
<p class="font-italic font-weight-bold text-muted">
<%=events.vendor%>
</p>
<p><strong>Start Date</strong><%=events.sdate%></p>
<p><strong>End Date</strong><%=events.edate%></p>
</div>
<p>Event Details <br>
<%=events.description.substring(0,100)%>
</p>
<p>
Find More
</p>
</div>
</div>
<%})%>
</div>
</div>
<%}%>
<!-- //Trying to filter all the promotions by vendor if vendor name= to promotions's vendor name only show in the show page-->
<%if(promo.vendor===vendor.name){%>
<div class = "container-fluid">
<div class = "row">
<%promo.forEach(function(promotions){%>
<div class="col-sm-6 col col-md-4 col-lg-3">
<div class="thumbnail">
<img src ="<%=promotions.image%>" class="rounded" width="304" height="236">
<div class="caption">
<h4><%=promotions.name%></h4>
<p class="font-italic font-weight-bold text-muted"> <%=promotions.vendor%></p>
<p><strong>Start Date</strong> <%=promotions.sdate%></p>
<p><strong>End Date</strong> <%=promotions.edate%></p>
</div>
<p>
<%=promotions.description.substring(0,100)%>
</p>
<p>
Find More
</p>
</div>
</div>
<%})%>
</div>
</div>
<%}%>
IMAGEThis is how ist's displayed on the web
I want to access the object part to display the data using EJS. I have failed to reach the object data.
My Schema
let Subject = mongoose.Schema({
name:[],
crh:[]
});
let Program = mongoose.Schema({
name: String,
semester: Number,
subject:[Subject]
});
let School = mongoose.Schema({
name:{
type: String,
},
program:[Program]
})
POST METHOD TO ACCESS THE DATE FROM THE DB
router.post('/view',(req,res) =>{
let school = req.body.school;
let semester = req.body.semester;
let program = req.body.program;
All.find({name:school,"program.name":program,"program.semester":semester},(err,record) =>{
if(err) throw err;
if(!record){
req.flash("error","We couldn't find any relevant document! ");
res.redirect('/admin/view');
}
if(record){
console.log(record);
res.render("./admin/viewSub",{find:record});
}
})
})
Consoled data! How do i access the data of the object from ejs. I want to display the data inside the object in table. I just want to know how to access it, when i try to use "." to reach the points; i am unable to reach the data.
[ { program: [ [Object] ],
_id: 5a9045474b530750a4e93338,
name: 'sose',
__v: 0 } ]
Try this.
<ul>
<li><%= find.name %></li>
</ul>
<ul>
<%for (var prog in find.program){%> //to fetch data from array of array
<li><%= prog.name %></li>
<li><%= prog.semester %></li>
<ul>
<% for (var sub in prog.subject){%>
<li><%= sub %></li>
<%}%>
</ul>
<%}%>
</ul>
I'm having difficulty connecting the dots with the router.params objects with express.
Right now I'd like to have the button-success button in the code below point to a url that reads someaddress.com/formula/:item._id
HTML: (EJS Templating Engine)
<% formulas.forEach(function(item){ %>
<div class="pure-u-1 pure-u-sm-1-2 pure-u-md-1-4 pure-u-xl-1-5">
<div class="formula-block centered" id="<%= item._id %>">
<h4 class="padded-top"> <%= item.name %></h4>
<p> <%= item.description %></p>
<button class="button-success pure-button">Show</button>
<button class="button-warning pure-button">Delete</button>
</div>
</div>
<% }); %>
I am pairing that with this Express route:
router.get('/formula/:id', function(req, res){
var db = req.db;
var collection = db.get('formulas');
var id = req.params.id;
collection.find({"_id": id}, {}, function(e, doc){
res.render('formula/:id', {
formula: doc,
title: `formula for ${doc.name}`,
description: `modify and view ${doc.name} formula`
});
});
});
which then uses the information from the MongoDB document to generate the page.
It's not clear to me how you do this from looking at the documentation.
Thank you for your help.
I am trying to display my mongodb data in a bootstrap template.
api.js
var Software = require('../models/dbSoftware.js');
exports.show = (function(req, res) {
Software.find({Publisher: req.params.format}, function(error, softwares) {
res.render('searchpage', { searchText: req.params.format, softwares: softwares});
})
});
Software Schema:
var mongoose = require('mongoose');
var softwareSchema = new mongoose.Schema({
SoftwareName: String
, Size: String
, Publisher: String
, Product: String
, Version: String
, Language: String
, License_Type: String
, Description: String
, License_Key: String
});
module.exports = mongoose.model('Software', softwareSchema);
searchpage.ejs
<td><%= softwares.Product %></td>
This returns undefined value. Any softwares.* returns 'undefined'.
When I edit searchpage.ejs to:
<td><%= softwares%></td>
The output is:
{ License_Key: 'computing', Description: 'Licensed', License_Type: 'English', Language: 'UNKNOWN', Product: 'Test Test', Publisher: 'Test', Size: '231.6MB', SoftwareName: 'Test.zip', _id: 5252c407d9b28d1e4c000001, __v: 0 }
//which is correct
When using .find(), softwares will be an Array for all successful (error == null) queries, regardless of the number of documents found:
<%= softwares.length %>
<%= softwares[0].Product %>
If you only want a single document, you'll want to use .findOne() instead:
Software.findOne({Publisher: req.params.format}, function(error, softwares) {
// ...
});
<% if (softwares != null) { %>
<%= softwares.Product %>
<% } %>
Or, you can iterate over softwares:
<% softwares.forEach(function (software) { %>
<%= software.Product %>
<% }) %>