how can I apply multiply each as express handlebars (#each)? - node.js

.Handlebars file
{{#each products}}
<div class="col-xs-6 col-sm-4 col-md-4 col-lg-4">
<div class="product_block">
<div class="product-image-container image">
<a href="#" class="product_img_link">
<img src="{{**???**= /images/product-1-1.jpg}}" alt="product-1-1" class="img-product" />
<span class="product-additional">
<img src="{{**???**= /images/product-1-2.jpg}}" alt="product-1-2-back" />
</span>
</a>
.index.js
app.get('/collections/all', (req, res) => { res.render('collections/all', {
title: 'All Products',
products: [
'/images/product-1-1.jpg',
'/images/product-1-2.jpg',
'/images/product-2-1.jpg',
'/images/product-2-2.jpg'
] }); });
Q. As you can see, I want to apply like 'product-1-1' and 'product-1-2' each <img>
But How can I apply each <img> as {#each} ???
Because I have to repeat <div class="col->..
So it is hard to apply ?
Excuse me, please help me ~

I think you have to rearange your data. At least you will have the opportunities of the (dynamic) each loop instead of comparing (static) filenames.
products: [
{
front: '/images/product-1-1.jpg',
back: '/images/product-1-2.jpg',
altFront: 'product-1-1',
altBack: 'product-1-1-back'
},
{
front: '/images/product-2-1.jpg',
back: '/images/product-2-2.jpg',
alt: 'product-2-1',
altBack: 'product-2-1-back'
},
]
{{#products}}
<div class="col-xs-6 col-sm-4 col-md-4 col-lg-4">
<div class="product_block">
<div class="product-image-container image">
<a href="#" class="product_img_link">
<img src="{{front}}" alt="{{altFront}}" class="img-product" />
<span class="product-additional">
<img src="{{back}}" alt="{{altBack}}" class="img-product" />
</span>
</a>
</div>
</div>
</div>
{{/products}}

Related

How to display JSON object with Handlebars template

I am trying to create a react-like component with Handlebars. In this project, I have a set of project cards that are inside a carousel. The cards consist of a photo, project name, project description, and project link. The information is being pulled from an API that I create with the JSON data looking something like this
[
{
_id: '627b281c0ee7f8ee7eb08703',
name: 'Pamela',
about: "Pamela's portfolio page",
github: "pam's portfolio",
website: 'https://github.com/AlexAntoine/Devcamper-api/blob/main/models/Bootcamp.js',
tools: [ 'node js', 'Express', 'heroku', 'mongoDB', 'mongoose' ],
content: [],
__v: 0
},
{
_id: '627b284f0ee7f8ee7eb08706',
name: 'Mike',
about: "Mike's portfolio page",
github: "mike's portfolio",
website: 'https://github.com/AlexAntoine/Devcamper-api/blob/main/models/Bootcamp.js',
tools: [ 'node js', 'Express', 'heroku', 'mongoDB', 'mongoose', 'React' ],
content: [],
__v: 0
},
{
_id: '627b28b00ee7f8ee7eb08709',
name: 'Alex',
about: "Alex's portfolio page",
github: "alex's portfolio",
website: 'https://github.com/AlexAntoine/Devcamper-api/blob/main/models/Bootcamp.js',
tools: [
'node js',
'Express',
'heroku',
'mongoDB',
'mongoose',
'Angular'
],
content: [],
__v: 0
}
]
My goal is to have a new card created with the information from each object. For example, the first card would be populated with "Pamela", "Pamela's portfolio page", and "https://github.com/AlexAntoine/Devcamper-api/blob/main/models/Bootcamp.js " The starting HBS code I have for this is
{{#each this}}
{{>header}}
<section class="s1">
<div class="main-container">
<div class="greeting-wrapper">
<h1>Hello I'm Don-Alex 2</h1>
</div>
<div class="intro-wrapper" >
<div class="nav-wrapper">
<div class="dots-wrapper">
<div id="dot-1" class="browser-dots"></div>
<div id="dot-2" class="browser-dots"></div>
<div id="dot-3" class="browser-dots"></div>
</div>
<ul id="navigation">
<li>Contact</li>
</ul>
</div>
<div class="left-column">
<img id="profile-pic" src="https://images.unsplash.com/photo-1524502397800-2eeaad7c3fe5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80" alt="Profile Picture">
<h5 >Personalize Theme</h5>
<div id="theme-options-wrapper">
<div data-mode="light" class="theme-dot" id="light-mode"></div>
<div data-mode="blue" class="theme-dot" id="blue-mode"></div>
<div data-mode="green" class="theme-dot" id="green-mode"></div>
<div data-mode="purple" class="theme-dot" id="purple-mode"></div>
</div>
<p id="setting-note">*Theme options will be saved for<br>your next visit</p>
</div>
<div class="right-column">
<div id="preview-shadow">
<div id="preview">
<div id="corner-tl" class="corner"></div>
<div id="corner-tr" class="corner"></div>
<h3>What I Do </h3>
<p>Aspring software developer that enjoys building new things</p>
<div id="corner-br" class="corner"></div>
<div id="corner-bl" class="corner"></div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="s2">
<div class="main-container">
<div class="about-wrapper">
<div class="about-me">
<h4>More about me</h4>
<p>Love watching anime and taking naps. </p>
<hr>
<h4>Top Expertise</h4>
<p>What i'm good at Download Resume </p>
<div id="skills">
<ul>
<li>HTML</li>
<li>CSS</li>
<li>Javascript</li>
<li>React</li>
<li>Bootstrap</li>
</ul>
<ul>
<li>Node.js</li>
<li>Mongoose</li>
<li>Express</li>
<li>MongoDB</li>
<li>Heroku</li>
</ul>
</div>
</div>
<div class="social-links">
<img id="social-img" src="https://images.unsplash.com/photo-1618401471353-b98afee0b2eb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1488&q=80" alt="Github">
<h3>Find my latest projects on Github</h3>
Github
<br>
</div>
</div>
</div>
</section>
<section class="s1">
<div class="main-container s1-container">
<h3>Some of My Past Projects</h3>
<div class="post-wrapper">
<div id="carouselExampleInterval" class="carousel slide" data-ride="carousel" data-pause="hover">
<div class="carousel-inner">
<!--Add loop here. Figure out how that is going to work out. -->
<div class="carousel-item active container-fluid temp-container" data-interval="3000">
<div class="post">
<div class="card-container">
<img class="thumbnail" src="https://images.unsplash.com/photo-1514474959185-1472d4c4e0d4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1674&q=80" alt="">
<div class="post-preview">
<h6 class="post-title">{{this.name}}</h6>
<p class="post-intro">{{this.about}}</p>
1
</div>
</div>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleInterval" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleInterval" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
</section>
<section class="s2" id="one">
<div class="main-container">
<h3>Get In Touch</h3>
<form action="/" id="contact-form">
<label for="">Name</label>
<input type="text" class="input-field" name="name">
<label>Subject</label>
<input type="text" name="subject" class="input-field">
<label>Email</label>
<input type="text" name="email" class="input-field">
<label>Message</label>
<textarea class="input-field" name="message"></textarea>
{{!-- <input type="submit" name="submit-btn" value="send" id="submit-btn"> --}}
<input type="submit" value="send" id="submit-btn">
</form>
</div>
</section>
{{>footer}}
{{/each}}
The server-side code that sends the data is written like this
app.get('/home2', async(req, res)=>{
const {data:{result}}= await axios.get(`https://antoine-portfolio-api.herokuapp.com/api/v1/projects`);
const projects= result.map((projects)=>{
// console.log('line 62: ', project);
return projects;
});
res.render('home2',{
// title:'Alex home',
name: projects,
about: projects
})
})
I cannot get the program to display the project name and the description for all three of the projects listed. Any help would be appreciated. Thank you.

case with router-outlet in Angular

This is my case, I have a main login that I configure in my app-routing.module.ts
{
path:'',
redirectTo:'/login',
pathMatch: 'full'
},
{
path:'users',
component:UsuariosComponent
}
my login
<div class="container p-5">
<div class="row">
<div class="col-md-4 mx-auto">
<div class="card">
<div class="card-header">
Acceso al Sistema
</div>
<div class="card-body">
<form (submit)="login()" >
<div class="form-group">
<input type="text" [(ngModel)]="user.email" name="email" class="form-control" placeholder="Email" autofocus>
</div>
<div class="form-group">
<input type="password" [(ngModel)]="user.contrasenia" name="password" class="form-control" placeholder="Contraseña" >
</div>
<button type="submit" class="btn btn-primary btn-block">
Ingresar
</button>
</form>
</div>
</div>
</div>
</div>
</div>
then when logging in to the main component use route.navigate to / main
my app.component is like this
< router-outlet></router-outlet>
2.my main is like this main.component.html
<ul class="navbar-nav ml-auto"><!--mr-auto-->
<li class="nav-item">
<a class="nav-link" routerLink="/users" routerLinkActive="active">
<i class="material-icons">person</i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" style="cursor: pointer;" (click)="salir()" routerLinkActive="active">
<i class="material-icons">power_settings_new</i>
</a>
</li>
</ul>
<router-outlet></router-outlet>
my problem comes here when I want to access the routerlink /users, the nav or the ul where the routerlink had did not load, it takes me practically to another page, help me pls
Router-outlet only works for child routes. You need to have something like:
{
path:'',
component: Maincomponent,
children:[
{
path: 'users',
component: Usercomponent
}
]
}
And the router-outlet must be located in the parent Maincomponent html file

How to deal with this error?Cast to ObjectId failed for value "new" at path "_id" for model "arms"'

In arms.js file
router.get("/new",middleware.isLoggedIn,function(req,res){
res.render("arms/new");});
Below is my new.js file which i think is not causing any error.I think the problem is either in my header1.ejs or especially it is in my mongoose model schema of arms.
<%include ../partials/header1%>
<div class="container">
<div class="row">
<div class="col-md-10" offset="md-1">
<div class="row">
<div class="col-md-5 register-left">
<i class="far fa-hand-point-down"></i>
<h3>Join Us</h3>
<p>Sell your weapons here</p>
<button type="button" class="btn btn-primary">About Us</button>
</div>
<div class="col-md-7 register-right">
<h2>Place your Ad</h2>
<form action="/arms" class="register-form" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="name">
</div>
<div class="form-group">
<input type="number" class="form-control" name="price" placeholder="price" min="0.01" step="0.01">
</div>
<div class="form-group">
<input type="text" class="form-control" name="url" placeholder="url">
</div>
<div class="form-group">
<input type="text" class="form-control" name="description" placeholder="description">
</div>
<button type="button" class="btn btn-primary">Submit!</button>
</form>
</div>
</div>
</div>
</div>
</div>
<%include ../partials/footer%>
here is my header
<html lang="en">
<head>
<title>Arsenal</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="/public/stylesheets/main.css">
<link rel="stylesheet" href="/public/stylesheets/new.css">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">
Arms and Ammunition
<img src="https://img.icons8.com/nolan/64/000000/students.png">
</a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<%if(!currentUser){%>
<li class="nav-item">
<a class="nav-link" href="/register">Sign up</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login">Login</a>
</li>
<%}else{%>
<li class="nav-item">
<a class="nav-link" href="/logout">Signed In As <%=currentUser.username%></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Logout</a>
</li>
<%}%>
</ul>
</div>
</nav>
<div class="container">
<%if(error && error.length>0){%>
<div class="alert alert-danger" role="alert">
<%=error%>
</div>
<%}%>
<%if(success && success.length>0){%>
<div class="alert alert-success" role="alert">
<%=success%>
</div>
<%}%>
</div>
Well the the real thinn which is bothering me is that I am just sending a get req to this url http://localhost:3000/arms/new and as the above code suggest that whenever a get request is made just render new.ejs which is in folder arms (arms/new) and the i have given u the code of new.ejs which has no relation to mongoose model of arms I m just taking input in form nothing else I have the same code for another project which is working fine butt this is not
const mongoose = require("mongoose");
const armSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: String,
image: String,
description: String,
owner: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String,
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
})
module.exports = mongoose.model("arms", armSchema);
LAST EDIT: I made it actually the problem was that I was trying to make a get request to url arms/new and at the same time I was also handling request which were being sent to arms/:id/... so the problem was that mongoose was expecting :id of type mongoose type objectId which 'new' is obviously not so what I did is that I only placed the code of router.get("arms/new"...) above to the code of arms/:id/... so that whenever some one make a get req to arms/new first this router resolve the response so that it does not go to other routes but whenever a req to arms/mongoose.ObjectId is made then arms/new will fail and the req will go to arms/:id I hope it is clear now but if any of u guys fail do msg me i will resolve ur issue

User not defined issue for specific controller while passing data to view page in express nodejs

I am using express js as framework and ejs for view engine now for specific controller while passing data from controller to view it shows user not define with in view/partial/header.ejs which is working fine for other controller.
Controller code:
app.get('/add_home_content', function(req, res) {
User.findById(req.user, function(err, doc) {
if (doc.local.role == 'admin') {
var catId = '59f9be1aa40c152bc990f98f';
var contentid2 = '59faef18ce5da81b59c70a34';
var homeimgid = "59fc0e3e20942a15d7633cfd";
var contentplanid = "5a002bf79a62fc0bf2f14bbe";
content.findById(catId, function(err, content) {
//content.find({} ,{ "type": "homepage" }, function (err, content) {
//res.send(req.user.local);
trainercontent.findById(contentid2, function(err, trainercontent) {
homeimage.findById(homeimgid, function(err, homeimage) {
trainerinfo.find({}).exec(function(err, trainerinf) {
traininginfo.find({}).exec(function(err, traininginf) {
subscplancontent.findById(contentplanid, function(err, plancontent) {
banner.find({}).exec(function(err, bannerinf) {
// notification.find({}).exec(function(err, notifications) {
//res.send(content);
//trainercontent.find({}).exec(function(err, trainercontent) {
// res.send(notifications);
res.render('admin/content/addcontent.ejs', {
editContent: content,
editcontent2: trainercontent,
editcontent3: homeimage,
trainerinfo: trainerinf,
traininginfo: traininginf,
plancontents: plancontent,
bannerinfo: bannerinf,
message: false,
user: req.user.local
});
});
});
});
});
});
});
});
}
});
});
View page code(view engine ejs code) Showing user undefined error:
<script type="text/javascript">
/********signUp form validation *********/
$(document).ready(function() {
$('#planAdd').submit(function(e) {
var valid = $("#planAdd").valid();
if (valid) {} else {
e.preventDefault();
}
});
$('#planAdd').validate({
rules: {
'plan_name': 'required',
'price': 'required',
'currency': 'required',
'plan_duration': 'required'
},
messages: {
plan_name: {
required: "Plan can't be blank"
},
price: {
required: "Price can't be blank"
},
currency: {
required: "Currency can't be blank",
},
plan_duration: {
required: "Plan Duration can't be blank"
}
}
});
});
/********end of form validation *********/
</script>
<div class="page-inner">
<% if (message.length > 0) { %>
<div class="alert alert-danger">
<%= message %>
</div>
<% } %>
<div id="main-wrapper">
<a class="btn btn-success btn-lg " href="javascript: history.go(-1)">←Back To previous page</a>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8 add-plan-form">
<div class="row m-t-md">
<h1 class="add-plan-heading">Add Content</h1>
<script type="text/javascript">
$(document).ready(function(){
$("#myTab li:eq(0) a").tab('show');
});
</script>
<style type="text/css">
.bs-example{
margin: 20px;
}
.col-sm-8 {
width: 96.667%;
}
#media (min-width: 320px) and (max-width: 480px){
#myTab li {
width: 100%;
margin: 5px 0;
}
}
#media (min-width: 481px) and (max-width: 640px){
#myTab li {
width: 50%;
margin: 5px 0;
padding: 5px;
}
}
#media (min-width: 641px) and (max-width: 767px){
#myTab li {
width: 33%;
margin: 5px 0;
padding: 5px;
}
}
</style>
</head>
<body>
<div class="bs-example">
<ul class="nav nav-tabs" id="myTab">
<li><a data-toggle="tab" href="#sectionA">Home page content</a></li>
<li><a data-toggle="tab" href="#sectionB">Trainer content</a></li>
<li><a data-toggle="tab" href="#sectionc">Home page bottom content</a></li>
<li><a data-toggle="tab" href="#sectiond">Trainers</a></li>
<li><a data-toggle="tab" href="#sectione">Add training type</a></li>
<li><a data-toggle="tab" href="#sectionf">Subscription plan content</a></li>
<li><a data-toggle="tab" href="#sectiong">Add Banner</a></li>
</ul>
<div class="tab-content clearfix">
<div id="sectionA" class="tab-pane fade in active">
<form action="/updateContent?id=<%= editContent.id %>" method="POST" id="planAdd">
<div class="form-group">
<label>Content Heading</label>
<input type="text" class="form-control" name="content_heading" value="<%= editContent.content_heading %>">
</div>
<div class="form-group">
<label>Content Description</label>
<textarea rows="7" cols="50" name="content_desc" class="form-control" ><%= editContent.content_desc %>
</textarea>
<span class="Phon_err"></span>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectionB" class="tab-pane fade">
<form action="/updatetrainContent?id=<%= editcontent2.id %>" method="POST" id="categoryAdd">
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="heading" value="<%= editcontent2.heading %>">
</div>
<div class="form-group">
<label>Description</label>
<!-- <input type="text" class="form-control" name="desc"> -->
<textarea rows="7" cols="50" name="desc" class="form-control" ><%= editcontent2.desc %>
</textarea>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectionc" class="tab-pane fade">
<form action="/add_img?id=<%= editcontent3.id %>" method="post" id="videoAdd" enctype="multipart/form-data" >
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="title" value="<%= editcontent3.title %>" >
</div>
<div class="form-group img-d">
<label > Thumbnail</label>
<div "><input type="file" class="" id="e_Img_file" name=" home_img"></div>
<img src="./uploads/homepageimage/<%= editcontent3.home_img %>" height="200" width="220">
<span class="value"></span>
</div>
<button type="submit" class="btn btn-success btn-lg pull-right">Save</button>
</form>
</div>
<div id="sectiond" class="tab-pane fade in active m-div clearfix">
<h2 class="h-div">
Add new trainer</h2>
<!-- <% if(trainerinfo){ trainerinfo.forEach( function (trainerinf){ %>
<div class="members animated fadeInLeft visible" data-animation="fadeInLeft" data-animation-delay="300"><div class="content_slider_text_block_wrap"><div class="team-img"><img src="/uploads/trainerprofile/<%- trainerinf.trainer_profile %>" alt="image" class="member_photo" width="250" height="320"></div><div class="team-inner"><div class="team-top center"><h4 class="membername"><%- trainerinf.trainer_name %></h4><br><span class="membername_dec"><%- trainerinf.trainig_type %></span></div></div></div><div class="clear"></div></div><div class="sharemedeia"><a target="_self" href="<%- trainerinf.trainer_facebook %>"><i class="fa fa-facebook"></i></a><a target="_self" href="<%- trainerinf.trainer_twiter %>"><i class="fa fa-twitter"></i></a><a target="_self" href="<%- trainerinf.trainer_google %>"><i class="fa fa-google-plus"></i></a></div>
Edit
Delete
<% }); }%> -->
<div class="members_section">
<div class="row">
<% if(trainerinfo){ trainerinfo.forEach( function (trainerinf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/trainerprofile/<%- trainerinf.trainer_profile %>" alt="image" class="member_photo img-responsive">
<h4 class="membername"><%- trainerinf.trainer_name %><span class="membername_dec">(<%- trainerinf.trainig_type %>)</span></h4>
<div class="sharemedeia">
<a target="_self" href="%- trainerinf.trainer_facebook"><span class="s-bg"><i class="fa fa-facebook"></i></span></a>
<a target="_self" href=""<%- trainerinf.trainer_twiter %>"><span class="s-bg"><i class="fa fa-twitter"></i></span></a>
<a target="_self" href="<%- trainerinf.trainer_google %>"><span class="s-bg"><i class="fa fa-google-plus"></i></span></a></div>
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
<div id="sectione" class="tab-pane fade in active">
<h2 class="h-div"><a href="/addtrainingtype" >Add new training type</a></h2>
<div class="members_section">
<div class="row">
<% if(traininginfo){ traininginfo.forEach( function (traininginf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/trainingtype/<%- traininginf.training_profile %>" alt="image" class="member_photo img-responsive">
<h4 class="membername"><%- traininginf.trainer_title %></h4>
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
<div id="sectionf" class="tab-pane fade in active">
<form action="/subsplanContent?id=<%= plancontents.id %>" method="POST" id="planAdd">
<div class="form-group">
<label>Heading</label>
<input type="text" class="form-control" name="title" value="<%= plancontents.title %>" >
</div>
<div class="form-group">
<label>Content Description</label>
<textarea rows="7" cols="50" name="content_desc" class="form-control" ><%= plancontents.content_desc %>
</textarea>
<span class="Phon_err"></span>
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
</div>
<div id="sectiong" class="tab-pane fade in active">
<h2 class="h-div">
Add banner image</h2>
<div class="members_section">
<div class="row">
<% if(bannerinfo){ bannerinfo.forEach( function (bannerinf){ %>
<div class="col-sm-4 col-xs-6 team_m">
<img src="/uploads/bannerimage/<%- bannerinf.banner_image %>" alt="image" class="member_photo img-responsive">
<div class="ed_de">
Edit
Delete
</div>
</div> <!--col-sm-4-->
<% }); }%>
</div> <!--row-->
</div> <!--members_section-->
</div>
</div>
</div>
</body>
</html>
</div>
</div>
</div>
</div>

how to display a single prouct from database in mongodb and node.js

we have created a e-commerce project in that while clicking on categories in UI it will renders to category page in that page it has show one product of each subcategory
i have written the code in which the entire products with the specific category name is displaying how i can remove the extra products as of now i required only one product of each sub category of the particular category
the routing code is
router.get("/shop/:category_name", function(req, res){
//querystring
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var viewModel = {
breadCrumb: [],
categories : [],
featuredProducts :[],
products : [],
};
viewModel.breadCrumb.push({
name : 'Home',
class : 'breadcrumb-ordinary'
});
viewModel.breadCrumb.push({
name : req.params.category_name,
class : 'breadcrumb-active'
});
async.parallel({
categories: function(cb){
Category.find({}, cb);
},
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
}, function(err, results) {
if (err) throw err;
viewModel.categories1=results.categories1;
viewModel.categories=results.categories;
res.render('shop/prod_grid',viewModel);
});
});
the view UI code is
<!doctype html>
<html lang="en-US"> <!--<![endif]-->
<head>
</head>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="../../../shop-plugins/css/jplist-pagination.css">
<link rel="stylesheet" href="../../../shop-plugins/css/breadcrumb.css">
<body>
{{> shop/header}}
<!-- BAR -->
<div class="shipping-wrap">
<div class="container">
<div class="row">
<div class="span12">
<ul>
<li>
{{#each breadCrumb}}
{{#if #first}}
<a href="/" class="{{class}}">{{name}}
{{else}}
<a class="{{class}}">{{name}}
{{/if}}
{{#if #last}}
{{else}}
<i class="fa fa-angle-double-right"></i></a>
{{/if}}
{{/each}}
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- BAR -->
<!-- PRODUCT-OFFER -->
<div class="product_wrap">
<div class="container">
<div class="row">
<div id="span9" class="span9 product-grid">
<div id="products" class="box jplist jplist-grid-view">
<div class="jplist-panel box jplist-panel-top">
<div
class="jplist-drop-down"
data-control-type="items-per-page-drop-down"
data-control-name="paging"
data-control-action="paging">
<ul id="per-pages">
<li><span data-number="3">3 per page</span></li>
<li><span data-number="6" data-default="true">6 per page</span></li>
<li><span data-number="9">9 per page</span></li>
<li><span data-number="12">12 per page</span></li>
</ul>
</div>
<div
class="jplist-drop-down"
data-control-type="sort-drop-down"
data-control-name="sort"
data-control-action="sort">
<ul id="sorting">
<li><span data-path="default">Sort By</span></li>
<li><span data-path=".brand" data-order="asc" data-type="text">Brand A-Z</span></li>
<li><span data-path=".brand" data-order="desc" data-type="text">Brand Z-A</span></li>
<li><span data-path=".cost" data-order="asc" data-type="number">Cost Low-High</span></li>
<li><span data-path=".cost" data-order="desc" data-type="number">Cost High-Low</span></li>
</ul>
</div>
<div
class="jplist-label"
data-type="Page {current} of {pages}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-views"
data-control-type="views"
data-control-name="views"
data-control-action="views"
data-default="jplist-grid-view">
</div>
</div>
{{#each subcategoryprod}}
<div>
<ul>
<li>{{subcategory}}</li>
</ul>
</div>
{{/each}}
<!--category wise products-->
<div id="jp-panel" class="list box text_shadow">
{{#each subcategoryprod}}
<div id="jp-panel-item" class="list-item box">
<div class="span3 product">
<div>
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="" onerror="this.src='../../../shop-images/coming-soon.png'">
<div class="overlay">
</div>
{{/if}}
{{else}}
<img src="../../../shop-images/coming-soon.png" alt="">
<div class="overlay">
</div>
{{/each}}
</figure>
<div class="detail">
<span name="retailprice" class="cost">₹{{RetailPrice}}</span>
<span>{{colour}}</span>
<h4 class="brand">{{brand}}</h4>
<span>{{Description}}</span>
<div class="icon">
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
<div class="box jplist-no-results text-shadow align-center">
<p> No results Found</p>
</div>
<div class="jplist-panel box panel-bottom">
<div
class="jplist-label"
data-type="{start} - {end} of {all}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-pagination back-top"
data-control-animate-to-top="true"
data-control-type="pagination"
data-control-name="paging"
data-control-action="paging">
</div>
</div>
</div>
</div>
<div class="span3">
<div class="row">
</div>
<div id="sidebar">
<div class="widget">
<h4>Price Filter</h4>
<div class="price-range">
<div id="slider-range"></div>
<p class="clearfix">
<input type="text" id="amount" readonly />
<input type="text" id="amount2" readonly />
</p>
</div>
</div>
<div class="widget">
<h4>BRANDS</h4>
<div id="">
<div class="brands">
<input type='text' id='txtList' onkeyup="searchBrand(this)" placeholder="search brands here....." />
<!-- <ul id="fromList" class="myid"> -->
{{#each products}}
<ul id="fromList" class="myid">
<li> <input type="checkbox" id="{{brand}}" class="brandFilterCheckBox pull-right" align="center"/> <label for="{{brand}}">{{brand}}<label></li>
</ul>
{{/each}}
<!-- </ul> -->
</div>
</div>
</div>
</div>
<div class="widget">
<h4>CATEGORIES</h4>
<div id="accordion">
{{#each categories}}
<h5>{{category_name }}</h5>
<div>
<ul>
{{#each subcategories1}}
<li>{{subcategory_name}}</li>
{{/each}}
</ul>
</div>
{{/each}}
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Featured Products -->
<div class="container" style="margin-top:10px">
<div class="row heading-wrap">
<div class="span12 heading">
<h2>Featured Products <span></span></h2>
</div>
</div>
<div class="row similar_products">
<div id="feat_prod">
{{#each featuredProducts}}
<div class="span3 product">
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="">
<div class="overlay">
</div>
{{/if}}
{{/each}}
</figure>
<div class="detail">
<span>₹{{RetailPrice}}</span>
<h4>{{product_name}}</h4>
<span>{{Description}}</span>
</div>
</div>
{{/each}}
</div>
</div>
</div>
<!-- PRODUCT-OFFER -->
<!-- FOOTER -->
{{> shop/footer}}
<script type="text/javascript" src="../../../shop-plugins/js/jplist-pagination.js"></script>
<script src="../../../bootstrap/js/star.min.js"></script>
<script src="../../../shop-plugins/js/jquery.paginate.js"> </script>
<script>
$(function(){
$('#feat_prod').paginate();
});
</script>
<script>
$(document).ready(function(){
$('#products').jplist({
itemsBox: '.list'
,itemPath: '.list-item'
,panelPath: '.jplist-panel'
});
});
</script>
<script>
$('document').ready(function(){
$("#slider-range").slider({change : function(event,ui){
var lowerLimit=$("#amount").val();
var numberLowerLimit=Number(lowerLimit.substring(1,lowerLimit.length));
var upperLimit=$("#amount2").val();
upperLimit=upperLimit.substring(1,upperLimit.length);
var numberUpperLimit=Number(upperLimit.replace("₹",""));
console.log("LOWER LIMIT :"+lowerLimit+" UPPER LIMIT :"+upperLimit);
$(".cost").each(function(){
var rowUnitCost=$(this).text();
var unitCost=Number(rowUnitCost.substring(1,rowUnitCost.length));
if(unitCost<numberLowerLimit || unitCost>numberUpperLimit){
var hiddingBox=$(this).parents(".list-item");
/*hiddingBox.removeClass("list-item").addClass("rafsal-test");*/
hiddingBox.hide();
console.log("Values IN:"+unitCost);
}
else{
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
console.log("Values OUT:"+unitCost);
}
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
});
}
});
// Brand Filter
$(".brandFilterCheckBox").on('click',function(){
$(".brand").each(function(){
var hiddingBox=$(this).parents(".list-item");
hiddingBox.removeClass("list-item").addClass("rafsal-test");
hiddingBox.hide();
});
$(".brandFilterCheckBox").each(function(){
if($(this).prop("checked")){
var filterBrand=$(this).attr("id");
$(".brand").each(function(){
var unitBrandName=$(this).text().trim();
if(unitBrandName== filterBrand){
console.log(unitBrandName);
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
}
});
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
}
});
})
var textCheck="##";
removeDuplicateBrands()
});
function removeDuplicateBrands(){
var textCheck="##";
$(".brandFilterCheckBox").each(function(){
$(this).attr('id');
if(textCheck.indexOf("##"+$(this).attr('id')+"##")==(-1)){
textCheck=textCheck+$(this).attr('id')+"##";
}
else{
$(this).parent("li").hide();
}
});
}
</script>
<script>
function searchBrand(element) {
var value = $(element).val();
$("#fromList li").each(function () {
if ($(this).text().search(value) > -1) {
$(this).show();
$(this).prevAll('.header').first().show();
} else {
$(this).hide();
}
});
removeDuplicateBrands();
}
</script>
</body>
so i am posting a photo in which my output is there it contains all products of a specified category i need only one product from each sub category of the specified category and the image contains four products of protection category and two sub categories air freshners and Head unit , air freshners contains three products i need to display only one from airfreshner and one from head unit in which we need
In Your Router Code, Edit this section
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
Change the above to this
categories1:function(cb){
Category.findOne({category_name:req.params.category_name}, cb);
}
That should solve it for you.

Resources