'How to add cart items with respective user ID into database when user click add to cart button
when click add to cart button , i would like to save items to database with respective user id and product user selected. i already have cart schema and route cart js for add to cart , update cart, clear cart and check out. but i don't know how to save added item into database with respective user ID and show those save items from database into cart function. i would be soo appreciate if someone guide me into this one.
this is my cart model schema
var mongoose = require('mongoose');
var CartSchema = mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectID, ref: 'User' },
totalPrice: { type: Number, default: 0 },
items: [{
item: { type: mongoose.Schema.Types.ObjectID, ref: 'Product' },
qty: { type: Number, default: 1 },
price: {type: Number , default: 0},
image: { type: String }
}]
});
var Cart = module.exports = mongoose.model('Cart', CartSchema);
this is my product Schema
var mongoose = require('mongoose');
// Product Schema
var ProductSchema = mongoose.Schema({
title: {
type: String,
required: true
},
slug: {
type: String
},
desc: {
type: String,
required: true
},
category: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
image: {
type: String
}
});
var Product = module.exports = mongoose.model('Product', ProductSchema);
this is my add to cart ejs <%- include ('_layouts/header'); -%>
<form action="/products/<%= p._id %>/addCart" method="POST">
<div class="row">
<h1 class="page-header"><%= p.title %></h1>
<div class="col-xs-12 col-md-5">
<img class="spi" src="/product_images/<%= p.id %>/<%= p.image %>" alt="">
<br>
</div>
<div class="col-xs-12 col-md-7">
<p><%= p.desc %></p>
<p>$<%= parseFloat(p.price).toFixed(2) %></p>
<% if (loggedIn) { %>
<p> <button onclick="window.location.href='/cart/add/<%= p.slug %>';" class="btn btn-default"> <i class="fa fa-heart"></i></button> </p>
<% } else {%>
<p>You must be logged in to purchase items.</p>
<% } %>
</div>
<div class="col-xs-12">
<ul class="gallery">
<% galleryImages.forEach(function(image){ %>
<% if (image != "thumbs") { %>
<li>
<a data-fancybox="gallery" href="/product_images/<%= p.id %>/gallery/<%= image %>">
<img src="/product_images/<%= p.id %>/gallery/thumbs/<%= image %>" alt="">
</a>
</li>
<% } %>
<% }); %>
</ul>
</div>
</div>
</form>
<%- include ('_layouts/footer'); -%>
this is my cart js route . this is the part i don't know how to add save added item into cart and show the added item into cart function.
var express = require('express');
var router = express.Router();
// Get Product model
var Product = require('../models/product');
var cart = require('../models/cart');
/*
* GET add product to cart
*/
router.get('/add/:product', function (req, res) {
var slug = req.params.product;
Product.findOne({ slug: slug }, function (err, p) {
if (err)
console.log(err);
if (typeof req.session.cart == "undefined") {
req.session.cart = [];
req.session.cart.push({
title: slug,
qty: 1,
price: parseFloat(p.price).toFixed(2),
image: '/product_images/' + p._id + '/' + p.image
});
} else {
var cart = req.session.cart;
var newItem = true;
for (var i = 0; i < cart.length; i++) {
if (cart[i].title == slug) {
cart[i].qty++;
newItem = false;
break;
}
}
if (newItem) {
cart.push({
title: slug,
qty: 1,
price: parseFloat(p.price).toFixed(2),
image: '/product_images/' + p._id + '/' + p.image
});
}
}
// console.log(req.session.cart);
req.flash('success', 'Product added!');
res.redirect('back');
});
});
/*
* GET checkout page
*/
router.get('/checkout', function (req, res) {
if (req.session.cart && req.session.cart.length == 0) {
delete req.session.cart;
res.redirect('/cart/checkout');
} else {
res.render('checkout', {
title: 'Checkout',
cart: req.session.cart
});
}
});
/*
* GET update product
*/
router.get('/update/:product', function (req, res) {
var slug = req.params.product;
var cart = req.session.cart;
var action = req.query.action;
for (var i = 0; i < cart.length; i++) {
if (cart[i].title == slug) {
switch (action) {
case "add":
cart[i].qty++;
break;
case "remove":
cart[i].qty--;
if (cart[i].qty < 1)
cart.splice(i, 1);
break;
case "clear":
cart.splice(i, 1);
if (cart.length == 0)
delete req.session.cart;
break;
default:
console.log('update problem');
break;
}
break;
}
}
req.flash('success', 'Cart updated!');
res.redirect('/cart/checkout');
});
/*
* GET clear cart
*/
router.get('/clear', function (req, res) {
delete req.session.cart;
req.flash('success', 'Cart cleared!');
res.redirect('/cart/checkout');
});
/*
* GET buy now
*/
router.get('/buynow', function (req, res) {
delete req.session.cart;
res.sendStatus(200);
});
// Exports
module.exports = router;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
