Category Archives: Node.JS

Developing web application with Node.JS.

Building an e-Commerce website with Node – Part 47 – Remove button for cart in Node.js

We are going to add a “Remove” button so the user can remove a product from the cart. Open the main.js file in the routes folder and type in the following code. The cart.ejs file will be shown at the end of the article.

router.post('/remove', function(req, res, next) {
  Cart.findOne({ owner: req.user._id }, function(err, foundCart) {
    foundCart.items.pull(String(req.body.item));

    foundCart.total = (foundCart.total - parseFloat(req.body.price)).toFixed(2);
    foundCart.save(function(err, found) {
      if (err) return next(err);
      req.flash('remove', 'Successfully removed');
      res.redirect('/cart');
    });
  });
});

Continue reading

Building an e-Commerce website with Node – Part 46 – Create Cart Page in Node.js

We are going to create a cart page for our application. Open the views/main folder and create a new file named cart.ejs. Type in it the following code.

<% layout('layout') -%>

<div class="container">
  <div class="row">
    <div class="col-lg-6">
      <% for (var i = 0; i < foundCart.items.length; i++) { %>
        <div class="list-group">
          <span class="list-group-item">
            <div class="row">
              <div class="col-md-3">
                <span><img class="product-image" src="<%= foundCart.items[i].item.image %>"></span>
              </div>
              <div class="col-md-6">
                <p class="list-group-item-heading"><%= foundCart.items[i].item.name %></p>
              </div>
              <div class="col-md-3">
                <p><%= foundCart.items[i].quantity %></p>
                <p><%= foundCart.items[i].price %></p>
              </div>
            </div>
          </span>
        </div>
        <% } %>
      </div>
    </div>
  </div>

Continue reading

Building an e-Commerce website with Node – Part 45 – Create Cart Route in Node.js

Now, we are going to create a Cart route. Open the main.js in the routes folder and type in the following route just above the line router.post('/product/:product_id' ….

router.get('/cart', function(req, res, next) {
  Cart
    .findOne({ owner: req.user._id })
    .populate('items.item')
    .exec(function(err, foundCart) {
      if (err) return next(err);
      res.render('main/cart', {
        foundCart: foundCart,
        message: req.flash('remove')
      });
    });
});

Continue reading

Building an e-Commerce website with Node – Part 44 – Add interactivity to Plus and Minus buttons in Node.js

We have to add interactivity to our “+” and “-” buttons on the single product page. That means when the user clicks on the “+” button the quatity will increase by 1 and when the “-” button will be clicked the quantity will decrease by 1.

We do this in the custom.js file under the public/js folder. Open the file and type in the following code.

  $(document).on('click', '#plus', function(e) {
    e.preventDefault();
    var priceValue = parseFloat($('#priceValue').val());
    var quantity = parseInt($('#quantity').val());

    priceValue += parseFloat($('#priceHidden').val());
    quantity += 1;

    $('#quantity').val(quantity);
    $('#priceValue').val(priceValue.toFixed(2));
    $('#total').html(quantity);
  });


  $(document).on('click', '#minus', function(e) {
    e.preventDefault();
    var priceValue = parseFloat($('#priceValue').val());
    var quantity = parseInt($('#quantity').val());

    if (quantity == 1) {
      priceValue = $('#priceHidden').val();
      quantity = 1;
    } else {
      priceValue -= parseFloat($('#priceHidden').val());
      quantity -= 1;
    }

    $('#quantity').val(quantity);
    $('#priceValue').val(priceValue.toFixed(2));
    $('#total').html(quantity);
  });

Continue reading

Building an e-Commerce website with Node – Part 43 – Add to cart button in Node.js

Now we need an “Add to cart” button for our application. The button has to be on the product page so we have to modify the product.ejs page. We also need to add product information to the cart through a few forms. Open product.ejs, it is under the views/main folder, and type the following code.

<form method="post">
        <div class="btn-group" role="group" aria-label="...">
          <input type="hidden" name="quantity" id="quantity" value="1"></input>
          <button type="button" id="minus" class="btn btn-default">-</button>
          <button type="button" id="total" class="btn btn-default">1</button>
          <button type="button" id="plus" class="btn btn-default">+</button>
        </div>

        <div class="form-group">
          <input type="hidden" name="product_id" id="quantity" value="<%= product._id %>"></input>
          <input type="hidden" name="priceHidden" id="priceHidden" value="<%= product.price %>"></input>

          <input type="text" name="item" class="form-control" value="<%= product.name %>"></input>
          <input type="text" name="priceValue" id="priceValue" class="form-control" value="<%= product.price %>"></input>
        </div>

        <% if (user)  { %>
          <button type="submit" class="btn btn-primary btn-lg">Add to Cart</button>
        <% } else { %>
          <a href='/signup' class="btn btn-warning btn-lg">Signup to begin buying!</a>
        <% } %>
      </form>

Continue reading

Building an e-Commerce website with Node – Part 42 – Add product to cart in Node.js

Let’s create a post route so we can add to the cart a specific product. Under routes folder open the main.js file and type the following code under the last stream.on ... piece of code.

router.post('/product/:product_id', function(req, res, next) {
  Cart.findOne({ owner: req.user._id }, function(err, cart) {
    cart.items.push({
      item: req.body.product_id,
      price: parseFloat(req.body.priceValue),
      quantity: parseInt(req.body.quantity)
    });

    cart.total = (cart.total + parseFloat(req.body.priceValue)).toFixed(2);

    cart.save(function(err) {
      if (err) return next(err);
      return res.redirect('/cart');
    });
  });
});

Continue reading

Building an e-Commerce website with Node – Part 41 – Add cart quantity middleware in Node.js

Now, we are going to create a middleware that counts the length of the products in our cart. Basically, it tells you the quantity of the products you have into the cart.

We are going to create a new folder (under the root folder) and call it middlewares. In it, create a file and call it middleware.js. Type in this file the following code.

var Cart = require('../models/cart');

module.exports = function(req, res, next) {

  if (req.user) {
    var total = 0;
    Cart.findOne({ owner: req.user._id }, function(err, cart) {
      if (cart) {
        for (var i = 0; i < cart.items.length; i++) {
          total += cart.items[i].quantity;
        }
        res.locals.cart = total;
      } else {
        res.locals.cart = 0;
      }
      next();
    })
  } else {
    next();
  }
}

Continue reading

Building an e-Commerce website with Node – Part 39 – Shopping Cart Schema in Node.js

It is time to implement the shopping cart in our application. First of all we have to lay down the models for the cart. Basically we are going to create the CartSchema.

In the models folder create a new file and name it cart.js. Type in it the following code.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CartSchema = new Schema({
  owner: { type: Schema.Types.ObjectId, ref: 'User'},
  total: { type: Number, default: 0},
  items: [{
    item: { type: Schema.Types.ObjectId, ref: 'Product'},
    quantity: { type: Number, default: 1},
    price: { type: Number, default: 0},
  }]
});


module.exports = mongoose.model('Cart', CartSchema);

Continue reading

Building an e-Commerce website with Node – Part 38 – Instant search feature in Node.js

We are going to build an instant search feature for our application. In order to achieve that we are going to need three things.

  • A search API
  • We need to add additional HTML elements
  • A custom JavaScript file

Search API

Go to api folder and open the api.js file. In the file type the following code.

router.post('/search', function(req, res, next) {
  console.log(req.body.search_term);
  Product.search({
    query_string: { query: req.body.search_term }
  }, function(err, results) {
    if (err) return next(err);
    res.json(results);
  });
});

Continue reading