Node. js blog instance (11) Article search function
Now we will add the article search function for the blog, that is, fuzzy search for the article title based on the keyword, and the letters are case insensitive.
First, modify header. ejs and add a line of code before it:
Add a style row in style.css:
.search{border:0;width:6em;text-align:center;font-size:1em;margin:0.5em 0;}
Open post. js and add the following code at the end:
// Return all the Post information queried by the Title Keyword. search = function (keyword, callback) {mongodb. open (function (err, db) {if (err) {return callback (err);} db. collection ('posts', function (err, collection) {if (err) {mongodb. close (); return callback (err);} var pattern = new RegExp (^. * + keyword +. * $, I); collection. find ({title: pattern}, {name: 1, time: 1, title: 1 }). sort ({time:-1 }). toArray (function (err, docs) {mongodb. close (); if (err) {return callback (err) ;}callback (null, docs );});});});};
Note: We use pattern to define a regular expression that contains the keyword. If a keyword string starts or ends with a special character (for example, *), it must be escaped.
Modify index. js and add the following code before app. get ('/u/: name:
app.get('/search', function (req, res) {Post.search(req.query.keyword, function (err, posts) {if (err) {req.flash('error', err); return res.redirect('/');}res.render('search', {title: SEARCH: + req.query.keyword,posts: posts,user: req.session.user,success: req.flash('success').toString(),error: req.flash('error').toString()});});});
Create search. ejs in the views folder and add the following code:
<%- include header %>
- <% Var lastYear = 0%> <% posts. forEach (function (post, index) {%> <% if (lastYear! = Post. time. year) {%>
- <% = Post. time. year %>
- <% LastYear = post. time. year} %>
- <% = Post. time. day %>
- /<% = Post. time. day %>/<% = post. title %> <% = post. title %>
- <%}) %>
<%-Include footer %> Note: so far, you will find that tag. ejs and search. ejs code are exactly the same, because we use the same layout. This also highlights one of the advantages of the template-it can be reused, but we have not replaced these two files with one, because the name of each file represents a different meaning.
Effect: Enter the query keyword,
Query results: