Node.js: a search engine with autocomplete

Node.js: a search engine with autocomplete

Creating a search engine with the autocomplete feature is quite a simple task in Node.js.

Creating a search engine with the autocomplete feature is quite a simple task in Node.js.

We're going to use a Bootstrap plugin on the client side, namely Bootcomplete. This plugin sends via AJAX the search term and expects a JSON array of objects in response.

The default name of the query parameter is query (no pun intended), so we need to use this parameter in our Express route:


'use strict';

// General app settings

const Users = require('./models/Users');

app.post('/search', (req, res) => {
  let q = req.body.query;
  let query = {
    "$or": [{"name.first": {"$regex": q, "$options": "i"}}, {"name.last": {"$regex": q, "$options": "i"}}]
  };
  let output = [];

  Users.find(query).limit(6).then( usrs => {
      if(usrs && usrs.length && usrs.length > 0) {
          usrs.forEach(user => {
            let obj = {
                id: user.name.first + ' ' + user.name.last,
                label: user.name.first + ' ' + user.name.last
            };
            output.push(obj);
          });
      }
      res.json(output);
  }).catch(err => {
    res.sendStatus(404);
  });

});

The Mongo's $or operator used with regular expressions allows us to find users based on a match either in their first name or in their last name. Make sure to add the correct indexes to your collection for a faster and more efficient search.

Then our jQuery code will be as follows:


"use strict";

(function( $ ) {
    $(function() {
        $( "#q" ).bootcomplete({
          url: "/search",
          method: "post"
        });

    });
})( jQuery );

Complete code

Node.js: search with autocomplete