Listing 28.9 implements the route handling code for the Product
model. There are only two routes. The getProduct()
route finds a single product, based on the productId
included in the query. The getProducts()
route finds all products. If the requests are successful, the product or all products are returned to the client as JSON strings. If the requests fail, a 404 error is returned.
01 var mongoose = require('mongoose'),
02 Product = mongoose.model('Product'),
03 exports.getProduct = function(req, res) {
04 Product.findOne({ _id: req.query.productId })
05 .exec(function(err, product) {
06 if (!product){
07 res.json(404, {msg: 'Product Not Found.'});
08 } else {
09 res.json(product);
10 }
11 });
12 };
13 exports.getProducts = function(req, res) {
14 Product.find()
15 .exec(function(err, products) {
16 if (!products){
17 res.json(404, {msg: 'Products Not Found.'});
18 } else {
19 res.json(products);
20 }
21 });
22 };