The final schema is the customer schema. Listing 28.6 shows the full application schema including the CustomerSchema
on lines 42-48. The CustomerSchema
contains a unique userid
field to identify the customer and associate orders with the customer. This field would normally map to an authenticated session userid
.
Notice that the shipping, billing, and cart are all nested schemas. That makes it simple to define the model. You will see that each of these is accessed in the JavaScript, using shipping[0]
, billing[0]
, and cart[0]
array indexing. No cart object schema is necessary because it is inherently implemented by the array of ProductQuantitySchema
subdocuments.
01 var mongoose = require('mongoose'),
02 Schema = mongoose.Schema;
03 var AddressSchema = new Schema({
04 name: String,
05 address: String,
06 city: String,
07 state: String,
08 zip: String
09 }, { _id: false });
10 mongoose.model('Address', AddressSchema);
11 var BillingSchema = new Schema({
12 cardtype: { type: String, enum: ['Visa', 'MasterCard', 'Amex'] },
13 name: String,
14 number: String,
15 expiremonth: Number,
16 expireyear: Number,
17 address: [AddressSchema]
18 }, { _id: false });
19 mongoose.model('Billing', BillingSchema);
20 var ProductSchema = new Schema({
21 name: String,
22 imagefile: String,
23 description: String,
24 price: Number,
25 instock: Number
26 });
27 mongoose.model('Product', ProductSchema);
28 var ProductQuantitySchema = new Schema({
29 quantity: Number,
30 product: [ProductSchema]
31 }, { _id: false });
32 mongoose.model('ProductQuantity', ProductQuantitySchema);
33 var OrderSchema = new Schema({
34 userid: String,
35 items: [ProductQuantitySchema],
36 shipping: [AddressSchema],
37 billing: [BillingSchema],
38 status: {type: String, default: "Pending"},
39 timestamp: { type: Date, default: Date.now }
40 });
41 mongoose.model('Order', OrderSchema);
42 var CustomerSchema = new Schema({
43 userid: { type: String, unique: true, required: true },
44 shipping: [AddressSchema],
45 billing: [BillingSchema],
46 cart: [ProductQuantitySchema]
47 });
48 mongoose.model('Customer', CustomerSchema);