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);

So, we added two object id data type. One refers to the user and the other one refers to the product.
Every user will have a cart once he/she is signed up (the sign up route is going to be modified). The total will store the price, the total price.

The next field is the array of items. The items from the shopping cart will be displayed whenever the owner clicks on the cart URL.
The quantity is set to 1 by default so when the user buys a product the default quantity will be 1.

Leave a Reply