当我尝试从Mongoose访问MongoDB数据库时,Node.js Express应用程序冻结

时间:2012-08-21 02:48:35

标签: node.js mongodb express mongoose

我是Mongoose的新手,我正在尝试做一个简单的测试应用程序,涉及使用Mongoose以熟悉它。我可以很好地加载“/”页面,但是当我提交表单时,它会保留在“/”页面上,直到我终止该过程。 console.logs“之前”和“之后”打印,但是从来没有。有什么问题?

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);

1 个答案:

答案 0 :(得分:2)

首先,由于connectdb是一个异步函数,它会立即返回并稍后运行其回调 - 这意味着console.log的顺序将是"之前!&# 34;然后"之后!"然后"期间!"过了一会儿。

那就是说,connectdb并没有真正为你服务。 Mongoose会自动缓冲命令,直到它连接为止,因此您可以将其视为同步接口:

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);