I am new to Mongoose, and I am trying to do a simple test app that involves using Mongoose in order to familiarize myself with it. I can load up the "/" page fine, but when I submit the form, it stays on the "/" page until I terminate the process. The console.logs "before" and "after" print, but the during never does. What is wrong?
var express = require('express');
var mongoose = require('mongoose')
, db = mongoose.createConnection('localhost', 'testmongoose');
var connectdb = function(execute) {
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
execute();
});
};
connectdb(function () {
var postSchema = new mongoose.Schema({
body: String
});
var Post = db.model('Post', postSchema);
});
var app = express();
app.configure(function () {
//app.use(express.logger());
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
app.set('views', __dirname + '/views');
app.set('view engine','jade');
app.get('/', function(request, response) {
response.render('index');
});
app.post('/result', function(request, response) {
var text = request.body.text;
console.log("before!");
connectdb(function () {
console.log("during!");
var post = "test";
post = new Post({body: text});
response.render('result', {text: post.body});
});
console.log("after!");
});
app.listen(4000);
First of all, since connectdb
is an asynchronous function, it returns immediately and runs its callback later--meaning that the order of your console.log
s will be "before!" then "after!" and then "during!" sometime later.
That said, connectdb
isn't really serving you any use. Mongoose automatically buffers up commands until it connects, so you can treat it like a synchronous interface:
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost', 'testmongoose');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var postSchema = new mongoose.Schema({
body: String
});
var Post = mongoose.model('Post', postSchema);
var app = express();
app.configure(function () {
//app.use(express.logger());
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
app.set('views', __dirname + '/views');
app.set('view engine','jade');
app.get('/', function(request, response) {
response.render('index');
});
app.post('/result', function(request, response) {
var text = request.body.text;
var post = new Post({body: text});
response.render('result', {text: post.body});
});
app.listen(4000);