Implementing the Order Model Controller

Listing 28.10 implements the route handling code for the Order model. There are three routes. The getOrder() route finds a single order, based on the orderId included in the query. The getOrders() route finds all orders that belong to the current user. In this example, userid is hard-coded customerA. If the requests are successful, the order or all of this customer’s orders are returned to the client as JSON strings. If the requests fails, a 404 error is returned.

The addOrder() route handler builds a new Order object by getting the updated-Shipping, updatedBilling, and orderItems parameters from the POST request. If the order saves successfully, the cart field in the Customer object is reset to empty, using the following code, and a success is returned; otherwise, a 500 or 404 error is returned.

37       Customer.update({ userid: 'customerA' },
38           {$set:{cart:[]}})

Listing 28.10 orders_controller.js: Implementing routes to get and add orders for the Express server


01 var mongoose = require('mongoose'),
02     Customer = mongoose.model('Customer'),
03     Order = mongoose.model('Order'),
04     Address = mongoose.model('Address'),
05     Billing = mongoose.model('Billing'),
06 exports.getOrder = function(req, res) {
07   Order.findOne({ _id: req.query.orderId })
08   .exec(function(err, order) {
09     if (!order){
10       res.json(404, {msg: 'Order Not Found.'});
11     } else {
12       res.json(order);
13     }
14   });
15 };
16 exports.getOrders = function(req, res) {
17   Order.find({userid: 'customerA'})
18   .exec(function(err, orders) {
19     if (!orders){
20       res.json(404, {msg: 'Orders Not Found.'});
21     } else {
22       res.json(orders);
23     }
24   });
25 };
26 exports.addOrder = function(req, res){
27   var orderShipping = new Address(req.body.updatedShipping);
28   var orderBilling = new Billing(req.body.updatedBilling);
29   var orderItems = req.body.orderItems;
30   var newOrder = new Order({userid: 'customerA',
31                       items: orderItems, shipping: orderShipping,
32                       billing: orderBilling});
33   newOrder.save(function(err, results){
34     if(err){
35       res.json(500, "Failed to save Order.");
36     } else {
37       Customer.update({ userid: 'customerA' },
38           {$set:{cart:[]}})
39       .exec(function(err, results){
40         if (err || results < 1){
41          res.json(404, {msg: 'Failed to update Cart.'});
42         } else {
43          res.json({msg: "Order Saved."});
44         }
45       });
46     }
47   });
48 };


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.93.137