将问题直接放在代码中:
expressApp.get('/', function requestHandler(req, res) {
userMongooseModel.create(userPropertiesDict, NEVER_CALLED_CALLBACK);
console.log('This is printed just fine but browser awaits response forever.');
}
Express 是 3.x,Mongoose 是 3.x。
初始化的重要细节:
mongoose.connect(mongourl);
var mongoStore = require('connect-mongodb'); // Not 'connect-mongo', sic!
var store = new mongoStore({db: mongoose.connection.db}, resultHandler);
您可以在GitHub 上查看整个代码。
这是那里的主脚本的缩小版本:
var express = require('express'),
mongoose = require('mongoose')
mongoStore = require('connect-mongodb');
var app = express();
var mongourl = 'mongodb://localhost/problem_users';
var port = 9001;
console.log('Connecting to MongoDB...');
mongoose.connect(mongourl);
Schema = mongoose.Schema;
attributes = {
email: {
type: String,
required: true,
unique: true
}
};
schema = new Schema(attributes, {
strict: true
});
var User = mongoose.model('User', schema);
app.configure(function() {
app.use(express.cookieParser());
app.use(express.session({
secret: 'What bad can happen if I share this secret?',
maxAge: new Date(Date.now() + 60*60*1000),
store: new mongoStore({
db: mongoose.connection.db
}, function(err) {
return console.log(err || 'connect-mongodb setup ok');
})
}));
return app;
});
app.get('/', function(req, res) {
console.log('Ready to register a new user...');
var userPropertiesDict = {
email: 'some.email@example.com',
}
console.log('Calling User.create...');
User.create(userPropertiesDict, function(err, doc) {
console.log('WHY IS THIS MESSAGE NOT PRINTED AT ALL?');
var done = process.stdout.write('Are we stuck at flushing?');
if (!done) { // Is stdout blocked?
process.stdout.on('drain', _)
}
});
console.log('RESPONSE IS OVER. THIS MESSAGE IS PRINTED AT THE END AND WE HANG AFTERWARDS.');
});
app.listen(port);
console.log("Listening on port ", port);
console.log("MongoDB url ", mongourl);
console.log('Navigate your browser to http://localhost:%d', port);