简体   繁体   中英

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}}&nbsp;
                        {{else}}
                        <a class="{{class}}">{{name}}&nbsp;
                        {{/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><a href="/prod_grid?cat={{../category_name}}&subcat={{subcategory}}">{{subcategory}}</a></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}}
                                                                    <a href="#"><img src="../../../uploads/products/{{../_id}}/{{img}}" alt="" onerror="this.src='../../../shop-images/coming-soon.png'"></a>
                                                                    <div class="overlay">
                                                                        <a href="../../../uploads/products/{{../_id}}/{{img}}" class="zoom" width="1200" height="1200"></a>
                                                                        <a href="/prod_grid/{{../product_name}}/{{../product_no}}?cat={{../category}}&subcat={{../subcategory}}&tags={{../tags}}&brand={{../brand}}"  class="link"></a>

                                                                    </div>
                                                                {{/if}}
                                                                {{else}}
                                                                    <a href="#"><img src="../../../shop-images/coming-soon.png" alt=""></a>
                                                                    <div class="overlay">
                                                                        <a href="../../../shop-images/coming-soon.png" class="zoom" height="1200" width="1200"></a>
                                                                        <a href="/prod_grid/{{product_name}}/{{product_no}}?cat={{category}}&subcat={{subcategory}}&tags={{tags}}&brand={{brand}}"  class="link"></a>

                                                                    </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">
                                                                <a href="/shop/shopping-cart/{{product_no}}" class="one tooltip" title="Add to cart"></a>
                                                                <a href="/product-grid" class="two tooltip " title="Add to wishlist"></a>
                                                            </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">&nbsp;
            </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>&nbsp;&nbsp;<input type="checkbox" id="{{brand}}"  class="brandFilterCheckBox pull-right" align="center"/>&nbsp;&nbsp;<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><a href="#">{{category_name }}</a></h5>
                            <div>
                                <ul>
                                    {{#each subcategories1}}
                                        <li><a href="/prod_grid?cat={{../category_name}}&subcat={{subcategory_name}}">{{subcategory_name}}</a></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}}
                                                <a href="#"><img src="../../../uploads/products/{{../_id}}/{{img}}" alt=""></a>
                                                <div class="overlay">
                                                    <a href="../../../uploads/products/{{../_id}}/{{img}}" class="zoom prettyPhoto"></a>
                                                    <a href="/prod_grid/{{../product_name}}/{{../product_no}}?cat={{../category}}&subcat={{../subcategory}}&tags={{../tags}}&brand={{../brand}}"  class="link"></a>
                                                </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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM