Now that the application is done, you need to create the initial Customer
, Order
, and Product
documents in the database. There are several different ways to do this, such as using a database script or creating an admin interface for you application. To make it simple, this example includes a basic Node.js script to generate the data you’ve seen so far.
The code in Listing 28.30 shows a basic Node.js script that first cleans up, removing the customers, orders, and products collections. It then creates a Customer
document and an Order
document and then adds several Product
documents. It adds the Product
documents to the Customer
document’s cart and the Order
document’s items.
01 var mongoose = require('mongoose'),
02 var db = mongoose.connect('mongodb://localhost/cart'),
03 require('./models/cart_model.js'),
04 var Address = mongoose.model('Address'),
05 var Billing = mongoose.model('Billing'),
06 var Product = mongoose.model('Product'),
07 var ProductQuantity = mongoose.model('ProductQuantity'),
08 var Order = mongoose.model('Order'),
09 var Customer = mongoose.model('Customer'),
10 function addProduct(customer, order, name, imagefile,
11 price, description, instock){
12 var product = new Product({name:name, imagefile:imagefile,
13 price:price, description:description,
14 instock:instock});
15 product.save(function(err, results){
16 order.items.push(new ProductQuantity({quantity: 1,
17 product: [product]}));
18 order.save();
19 customer.save();
20 console.log("Product " + name + " Saved.");
21 });
22 }
23 Product.remove().exec(function(){
24 Order.remove().exec(function(){
25 Customer.remove().exec(function(){
26 var shipping = new Address({
27 name: 'Customer A',
28 address: 'Somewhere',
29 city: 'My Town',
30 state: 'CA',
31 zip: '55555'
32 });
33 var billing = new Billing({
34 cardtype: 'Visa',
35 name: 'Customer A',
36 number: '1234567890',
37 expiremonth: 1,
38 expireyear: 2020,
39 address: shipping
40 });
41 var customer = new Customer({
42 userid: 'customerA',
43 shipping: shipping,
44 billing: billing,
45 cart: []
46 });
47 customer.save(function(err, result){
48 var order = new Order({
49 userid: customer.userid,
50 items: [],
51 shipping: customer.shipping,
52 billing: customer.billing
53 });
54 order.save(function(err, result){
55 addProduct(customer, order, 'Delicate Arch Print',
56 'arch.jpg', 12.34,
57 'View of the breathtaking Delicate Arch in Utah',
58 Math.floor((Math.random()*10)+1));
59 addProduct(customer, order, 'Volcano Print',
60 'volcano.jpg', 45.45,
61 'View of a tropical lake backset by a volcano',
62 Math.floor((Math.random()*10)+1));
63 addProduct(customer, order, 'Tikal Structure Print',
64 'pyramid.jpg', 38.52,
65 'Look at the amazing architecture of early America.',
66 Math.floor((Math.random()*10)+1));
67 addProduct(customer, order, 'Glacial Lake Print',
68 'lake.jpg', 77.45,
69 'Vivid color, crystal clear water from glacial runoff.',
70 Math.floor((Math.random()*10)+1));
71 });
72 });
73 });
74 });
75 });;