Creating the Express Route Controller for the /words Route

First, you need to implement the route handler that will interact with the Word model to retrieve the words from MongoDB. Listing 29.16 implements the getWords() route handler for the /words route. This handler reads the limit, skip, sort, and direction parameters from the query and uses them to query the MongoDB database.

The getSortObj() function transforms the sort fields and direction into the sort object that will be used in the .sort() method on the Query object.

Listing 29.16 words_controller.js: Implementing the backend word route controller to support the /words route


01 var mongoose = require('mongoose'),
02     Word = mongoose.model('Word'),
03 exports.getWords = function(req, res) {
04   var sort = getSortObj(req);
05   var query = Word.find();
06   if(req.query.contains.length > 0){
07     query.find({'word' : new RegExp(req.query.contains, 'i')});
08   }
09   query.sort(sort)
10   .limit(req.query.limit)
11   .skip(req.query.skip)
12   .exec(function(err, word) {
13     if (!word){
14       res.json(404, {msg: 'Word Not Found.'});
15     } else {
16       res.json(word);
17     }
18   });
19 };
20 function getSortObj(req){
21   var field = "word";
22   if(req.query.sort == 'Vowels'){
23     field = 'stats.vowels';
24   } else if(req.query.sort == 'Consonants'){
25     field = 'stats.consonants';
26   } else if(req.query.sort == 'Length'){
27     field = 'size';
28   }else{
29     field = req.query.sort.toLowerCase();
30   }
31   var sort = new Object();
32   sort[field] = req.query.direction;
33   return sort;
34 };


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

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