Advertisement
tourniquet

Simple search in Express and Mongoose

Jul 1st, 2015
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // html
  2. <form id="searchForm" action="/results" method="POST" enctype="multipart/form-data">
  3.   <input type="text" id="search" name="search" placeholder="search" />
  4. </form>
  5.  
  6.  
  7. // ExpressJS
  8. app.post('/results', (req, res) => {
  9.   const form = new formidable.IncomingForm()
  10.  
  11.   form.parse(req, (err, field) => {
  12.     if (err) console.log(err)
  13.  
  14.     const rawRequest = field.search
  15.     const keyword = rawRequest.toLowerCase().trim().replace(/\W+\D+/gim, "")
  16.  
  17.     // in MongoDB you need to have 'keywords' field
  18.     var query = contact.find({ keywords: { $regex: keyword } })
  19.     query.exec(function(err, contact) {
  20.       if (err) console.log(err)
  21.  
  22.       res.render('results.html', {
  23.         contacts: contact
  24.       })
  25.     })
  26.   })
  27. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement