Reputation: 294
So I am trying to make a live search feature where a user can search for other users based on username and the relevant results will be shown on the webpage. So far, I have only come across resources that show how to do this for PHP and MySQL. How can this be achieved for Node.js and MongoDB? I'm using socket.io in my project, could this be used at all?
Thanks for the help, and if any of my code is needed, just let me know!
Upvotes: 0
Views: 7002
Reputation: 390
In your requirement, it doesn't depend much on which backend to use.
On the backend just create a rest API to handle the search request (if you want to use NodeJS, you can refer this article https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4).
On the frontend, you can use just XHR request to make live search, no need socket. Each time user type on an input, detect the input change event and send the search request to the backend api (you can do it by just pure javascript XHR request, or use ajax module in JQuery ...), fetch the result from response, print to the screen. After you can achieve this, you can improve your search performance on the frontend by limiting request in amount of time (not sending request each time use press a key, but after an amount of time, example each 200ms, this technique call "debounce").
Upvotes: 3
Reputation: 116
Basically, you would watch when the user writes in the username input field( using the keyup event) and send the value of the input field to the server using socket.io, on the server, when you receive the value in the event you will do a query on the database(model.findOne in mongoose) with that value and return the user if he exists. The key here is to make the database do an index on the username for a faster search by making the username field unique in mongoose or by creating a new index manually.
Example:
Frontend with jquery:
$(document).ready(function() {
var username = $('#username');
username.keyup(function() {
var value = username.val();
socket.emit('find_user', value);
});
});
socket.on('find_user_result', function(user) {
// treat result here
});
Backend with mongoose:
socket.on('find_user', function(value) {
User.findOne({username: value}, function(err, user) {
if (err) throw err;
if (!user) socket.emit('find_user_result', {});
else socket.emit('find_user_result', user);
});
})
Upvotes: 4