Hướng dẫn find trong nodejs - tìm trong nodejs

Mở Đầu

Tiếp tục với series Nodejs cơ bản trong bài hôm nay mình sẽ giới thiệu về Query Parameters và ứng dụng nó để làm chức năng tìm kiếm. Vậy trước khi đi vào xây dựng chức năng tìm kiếm thì chúng ta cần phải biết Query Parameters là gì.

Nói một cách dễ hiểu thì Query Parameters là một chuỗi truy vấn thuộc URL(Uniform Resource Locater), nó đi sau dấu

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
0. Nó sẽ gửi data lên trên server. server dựa vào các data được gửi lên làm tham số để truy vấn vào cơ sở dữ liệu, lọc ra các kết quả. Trên
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
1 cũng sử dụng rất nhiều Query Parameters ví dụ như :

Hướng dẫn find trong nodejs - tìm trong nodejs

Các truy vấn sẽ bắt đầu từ sau dấu ? , theo từng cặp

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
3 và
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
4, nếu có nhiều hơn 1 truy vấn thì các truy vấn sẽ cách nhau bởi dấu
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
5 . Ok vậy là đã hiểu cơ bản về Query Parameters bây giờ chúng ta sẽ bắt tay vào làm chức năng tìm kiếm.

Xây dựng chức năng tìm kiếm

Ý tưởng

Ở đây mình định xây dựng chức năng tìm kiếm bài viết theo

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 hoặc theo
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
8. Vậy thì cần những gì:

  • Trước hết chúng ta cần phải có data để xây dựng trang danh sách bài viết
  • Tiếp theo cần có một trang view để hiển thị danh sách bài viết đó
  • Và một ô input để có thể nhập
    app.get('/', function(req, res){
        res.render('index', {
            posts: posts
        });
    })
    
    7 hoặc
    app.get('/', function(req, res){
        res.render('index', {
            posts: posts
        });
    })
    
    8 để thực hiện tìm kiếm trong danh sách đó.

Thực hiện

Đầu tiên là phải có data mà chúng ta chưa học kết nối với cơ sở dữ liệu (mongoDB) nên ở đây mình sẽ tạo ra một array để lưu thông tin của các bài viết. Vì mỗi bài viết là một obj nên ta sẽ có mảng

.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
1 trong file index.js như sau:

var posts = [
    {id:1, title: 'Nodejs cơ bản'},
    {id:2, title: 'Học vuejs'},
    {id:3, title: 'Javascrip'}
]

Vậy là đã xong phần đầu tiên là tạo data, tiếp theo sẽ là xây dựng trang view để hiển thị đống data mà chúng ta vừa tạo ở trên, Bài trước chúng ta đã tạo ra 1 file là

.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
2 nên mình sẽ sử dụng file đó luôn, chỉ cần chỉnh sửa một chút là được, Để bên file
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
2 có thể nhận được data thì chúng ta cần phần truyền data sang vì thế hàm dùng để
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
4 file
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
2 mình sẽ sửa lại như sau để có theer truyền được data sang.

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})

Tiếp theo mình cần sửa bên file

.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
2 để có thể hiện thị được danh sách bài post như sau

.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title

Ở đây có dùng vòng lặp

.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
7 của
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
8 để lấy ra hết các phần tử trong mảng
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
1. Muốn lấy giá trị thì chỉ cần
 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
0 đến thuộc tính của nó là được. Đây là kết quả sau khi chạy

Hướng dẫn find trong nodejs - tìm trong nodejs

OK (ngon) thế là chúng ta đã lấy hoàn thành xong trang danh sách bài post. Tiếp theo sẽ là thêm một ô

 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
1 để thực hiện gửi Query Parameters lên cho thằng server xử lý.chỉ cần thêm đoạn này vào
 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
3 là được

 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search

Ok bây giờ là đến việc của server. Ý tưởng của mình sẽ là tạo một router để thực hiện chức năng tìm kiếm bài post theo

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 mà client gửi lên.Router đó phải lấy được
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 từ client gửi lên và dùng hàm
 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
6 để filter ra những bài post trong mảng
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
1 có
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 bằng với
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 dưới client gửi lên. Và cuối cùng là lấy data sau khi đi qua hàm
 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
6 để render lại ra view. Nếu các bạn chưa rõ về
 form(action="/search", method="GET")
    input(name="id", type="text", placeholder="id")
    button Search
6 thì có thể xem lại bài Một số array method của javascript thường dùng này của mình nhé . còn đây là code
Hướng dẫn find trong nodejs - tìm trong nodejs
. còn đây là code

app.get('/search', function(req, res){
    var id = req.query.id;
	var data = posts.filter(function(item){
        return item.id === parseInt(id)
    });
	res.render('index', {
		posts: data
    });
})

Bây giờ ra trình duyệt để xem kết quả nhé

Hướng dẫn find trong nodejs - tìm trong nodejs

Một lưu ý nhỏ là

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 mà mình lấy được từ dưới client gửi lên đang ở kiểu string nên mình cần ép kiểu nó lại bằng
app.get('/search', function(req, res){
    var id = req.query.id;
	var data = posts.filter(function(item){
        return item.id === parseInt(id)
    });
	res.render('index', {
		posts: data
    });
})
3 thì mới so sánh được với
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
7 trong mảng
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
1 nhé.

Tương tự với tìm kiếm theo

app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
8 bạn chỉ cần viết lại hàm tìm kiếm như này

app.get('/search', function(req, res){
    var title = req.query.title;
	var data = posts.filter(function(item){
        return item.title.toLowerCase().indexOf(title.toLowerCase()) !== -1
    });
	res.render('index', {
		posts: data
    });
})

Ở đây có dùng hàm

app.get('/search', function(req, res){
    var id = req.query.id;
	var data = posts.filter(function(item){
        return item.id === parseInt(id)
    });
	res.render('index', {
		posts: data
    });
})
7 để chuyển hết data về chữ thường cho tiện việc so sánh. Và hàm
app.get('/search', function(req, res){
    var id = req.query.id;
	var data = posts.filter(function(item){
        return item.id === parseInt(id)
    });
	res.render('index', {
		posts: data
    });
})
8 để kiểm tra xem
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
8 mà client gửi lên có nằm trong
app.get('/', function(req, res){
    res.render('index', {
        posts: posts
    });
})
8 trong mảng
.posts
  head
    style.
      table, th, td {
      border: 1px solid black;
      }
  table
    thead
      tr
        th  Id
        th  Title
    tbody
    each post in posts
      tr
        td=  post.id
        td=  post.title
1 không nếu không thì sẽ trả về
app.get('/search', function(req, res){
    var title = req.query.title;
	var data = posts.filter(function(item){
        return item.title.toLowerCase().indexOf(title.toLowerCase()) !== -1
    });
	res.render('index', {
		posts: data
    });
})
2.

Kết Luận

Như vậy là mình đã giới thiệu cho các bạn về Query Parameters và làm thử chức năng tìm kiếm. Tuy nhiên còn cần cải thiện thêm một số chỗ nữa. Mình sẽ để giành ở bài tiếp theo. Mọi người có thắc mắc hay góp ý gì thì hãy comment xuống bên dưới để mình được biết, xin cảm ơn các bạn đã theo dõi.