1

我是 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);
4

1 回答 1

2

首先,由于connectdb是一个异步函数,它立即返回并稍后运行它的回调——这意味着你console.log的 s 的顺序将是“之前!” 然后!” 然后是“期间!” 一段时间以后。

也就是说,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);
于 2012-08-21T03:50:41.503 回答