node.js express mongodb save messages?

Problem

I'm trying to see express, mongoose and mongodb work togetter, in a really simple way. If I can have a box, put my name in there, submit it and have it save to the db, that's all i need. I tried doing this from taking pieces of tutorials but I'm stuck. I was trying to do it through a chat and just save every message. If you can get my example to work or have one of your own, either way, I't just helps me see something that works. Then I can have a foundation of what works and can add to it. I see a lot of tutorials and everything else, but not something simple for people, it's always a big project you get lost on somewhere, hopefully this will be helpfully to others too, it's a lot, with everything, with node and all it's friends. With my example I am not getting any errors, that I see, but there maybe some. And I'm looking in db chat to see the messages using db.messages.find() but there not in there.

my html

<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat{
height:500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>

<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 $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');

$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});

socket.on('new message', function(data){
$chat.append(data + "<br/>");
});
});

var chatSchema = mongoose.Schema({
msg: String,
created: {type: Date, default: Date.now}
});

var Chat = mongoose.model('Message', chatSchema);

var newMsg = new Chat({msg: msg});
        newMsg.save(function(err){
            if(err) throw err;
});               


</script>
</body>
</html>

the app

var mongoose = require('mongoose')
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3000);

app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});

mongoose.connect('mongodb://localhost/chat', function(err){
if(err){
console.log(err);
} else{
    console.log('Connected to mongodb!');
}
});
Problem courtesy of: user3081020

Solution

I've tried it and the modified version bellow works! The main changes where putting the mongoose schema code on the server side, and echo back the content of the text box on the server only after a successful save in the Mongo database.

Have a look also at the mean.io site for introduction to the MEAN stack, let me know if you have questions on the code.

Modified server.js:

var mongoose = require('mongoose')
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3000);

app.get('/', function(req, res){
    res.sendfile(__dirname + '/test.html');
});

io.sockets.on('connection', function(socket){
    socket.on('send message', function(data){

        var newMsg = new Chat({msg: '' + data});

        console.log('saving newMsg: ' + newMsg);

        newMsg.save(function(err){
            console.log('saved, err = ' + err);
            if(err) throw err;
            console.log('echoeing back data =' + data);
            io.sockets.emit('new message', data);
        });

    });
});

var chatSchema = mongoose.Schema({
    msg: String,
    created: {type: Date, default: Date.now}
});

var Chat = mongoose.model('Message', chatSchema);



mongoose.connect('mongodb://localhost/test', function(err){
if(err){
console.log(err);
} else{
    console.log('Connected to mongodb!');
}
});

This is the html page:

<html>
    <head>
        <title>Chat with socket.io and node.js</title>
        <style>
            #chat{
                height:500px;
            }
        </style>
    </head>
    <body>
        <div id="chat"></div>

        <form id="send-message">
            <input size="35" id="message"></input>
            <input type="submit"></input>
        </form>

        <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 $messageForm = $('#send-message');
                var $messageBox = $('#message');
                var $chat = $('#chat');

                $messageForm.submit(function(e){
                    e.preventDefault();
                    socket.emit('send message', $messageBox.val());
                    $messageBox.val('');
                });

                socket.on('new message', function(data){
                    console.log('Received data: ' + data);
                    $chat.append(data + "<br/>");
                });
            });

        </script>

    </body>
</html>
Solution courtesy of: Angular University

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.