so i'm building an basic chat application for my app and it mostly works and it is saving the messsages to my mongodb database. The problem is that the app isn't get the previous messages from the database and displaying them when you start it up.
chat model
// Dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema for chat
var ChatSchema = mongoose.Schema({
nick: String,
created:{ type: Date, default: Date.now},
msg: String,
displayName: [{type:String, ref: 'User' }],
room: String
});
// create a model from the chat schema
module.exports = mongoose.model('Message', ChatSchema);
socketio in node.js
socket.io
var server = http.createServer(app).listen(8000);
var io = require('socket.io')(server);
io.sockets.on('connection', function(socket) {
var query = Chat.find({});
query.limit(8).exec(function(err,docs) {
if(err) throw err;
socket.emit('load old msgs', docs);
});
socket.on('new user', function(data, callback){
if (data in users){
callback(false);
} else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', Object.keys(users));
}
socket.on('send message', function(data, callback){
var msg = data.trim();
console.log('after trimming message is: ' + msg);
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
if(ind !== -1){
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if(name in users){
users[name].emit('whisper', {msg: msg, nick: socket.nickname});
console.log('message sent is: ' + msg);
console.log('Whisper!');
} else{
callback('Error! Enter a valid user.');
}
} else{
callback('Error! Please enter a message for your whisper.');
}
} else{
var newMsg = new Chat ({msg: msg, nick: socket.nickname});
newMsg.save(function (err) {
if(err) throw err;
io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
});
}
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});
index.html
<style>
#chat{
height:500px;
}
#contentWrap{
display: none;
}
#chatWrap{
float: left;
border: 1px #000 solid;
}
.error{
color: red;
}
.whisper{
color: gray;
font-style: italic;
}
</style>
<div id="nickWrap">
<p>Enter a username:</p>
<p id="nickError"></p>
<form id="setNick">
<input size="35" id="nickname"></input>
<input type="submit"></input>
</form>
</div>
<div id="contentWrap">
<div id="chatWrap">
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</div>
<div id="users"></div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $nickBox.val(), function(data){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else{
$nickError.html('That username is already taken! Try again.');
}
});
$nickBox.val('');
});
socket.on('usernames', function(data){
var html = '';
for(var i=0; i < data.length; i++){
html += data[i] + '<br/>'
}
$users.html(html);
});
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val(), function(data){
$chat.append('<span class="error">' + data + "</span><br/>");
});
$messageBox.val('');
});
socket.on('load old msgs', function(docs) {
for(var i=0; i < docs.length; i++) {
displayMsg(docs[i]);
}
});
socket.on('new message', function(data){
displayMsg(data);
});
function displayMsg (data) {
$chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
}
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
});
});
</script>
via Jason Tran
No comments:
Post a Comment