Here is what I have accomplished rather than using the setInterval method in case someone wants to know how i did it on my project. Thanks to @Mariusz comment
"how about a simple HTTP webservice called by the one who writes to the database?"
gave me an idea. Instead, what I did is add an event click method on the form submit with socket.emit('client_data', {'data': $(this).serializeArray()});
to send the data to the server. Then on the server I call socket.on('client_data') method to fetch the data from the client to save it to the database and called io.sockets.emit method from the callback to send back the updated data to the client (reference on how to send responses to clients). Sorry if can't explain it even better, but here's the code so you could figure it out.
Client
<script src="/js/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<form id="form" method="post">
<label for="name">Name: <input id="text"type="text" name="name"></label>
<button id="submit" name="submit">save</button>
</form>
<ul id="names">
{% if datas %}
{% for data in datas %}
<li>{{data.name}}</li>
{% endfor %}
{% else %}
<li>No data</li>
{% endif %}
</ul>
<script>
$(document).ready(function(){
var socket = io.connect();
socket.on('data', function (data) {
if (data) {
$('#names').html('');
$.each(data.datas, function (index, value) {
$('#names').append('<li>'+ value.name +'</li>')
})
};
});
$('#form').on('submit', function(e){
e.preventDefault();
socket.emit('client_data', {'data': $(this).serializeArray()});
$('#text').val('').focus();
})
});
</script>
Server
io.on('connection', function (socket) {
socket.on('client_data', function(data){
Data.create({
name: data.data[0].value
}, function (err, newData) {
console.log(newData.name + ' is now saved in the database.')
Data.find({}, {name:1, _id:0}, {sort : { _id : -1 }}, function (err, data) {
if (err) {
console.log(err);
} else {
io.sockets.emit('data', {datas: data});
};
})
})
});
});
Now everytime a user/client updates the data, all the page will be updated as well without using setInterval to refresh the data. Hope it helps!