Node.js 部落格執行個體(十一)文章檢索功能

來源:互聯網
上載者:User

Node.js 部落格執行個體(十一)文章檢索功能

 

現在我們來給部落格增加文章檢索功能,即根據關鍵字模糊查詢文章標題,且字母不區分大小寫。
首先,我們修改 header.ejs ,在 前添加一行代碼:

 

在 style.css 中添加一行樣式:

 

 

.search{border:0;width:6em;text-align:center;font-size:1em;margin:0.5em 0;}
開啟 post.js ,在最後添加如下代碼:
//返回通過標題關鍵字查詢的所有文章資訊Post.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);});});});};
注意:我們通過 pattern 定義了包含關鍵字 keyword 的Regex,若 keyword 字串的開頭或結尾包含特殊字元(比如說 * )則需轉義。
修改 index.js ,在 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()});});});
在 views 檔案夾下建立 search.ejs ,添加如下代碼:
<%- 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 %> 注意:目前為止,你會發現 tag.ejs 和 search.ejs 代碼完全一樣,因為我們都用相同的布局。這也突出了模版的優點之一 —— 可以重複利用,但我們這裡並沒有把這兩個檔案用一個代替,因為每一個檔案的名字代表了不同的意義。

 

效果:輸入查詢關鍵字,

查詢結果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.