1

将问题直接放在代码中:

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

1 回答 1

1

请注意,此问题包括connect-mongodb,而不是connect-mongo。从 切换connect-mongodb到 以connect-mongo更优雅的方式解决问题,因此您应该先尝试一下。以下仅与有关connect-mongodb

我发现这个问题根本不涉及express。实际上它处理初始化mongoose连接和connect-mongodb会话的顺序。

初始化会话时connect-mongodb,数据库必须已经连接。由于mongoose.connect是异步执行的,当会话在连接完成之前初始化时,您很容易遇到问题(就像我所做的那样)。

可悲的一面是,由于某种原因connect-mongodb不会抛出或传递错误。

您可以在下面的代码中看到正确和错误的方式mongooseconnect-mongodb初始化。

var mongoose = require('mongoose')
    mongoStore = require('connect-mongodb');

var mongourl = 'mongodb://localhost/problem_users';

console.log("MongoDB: url ", mongourl);
console.log('MongoDB: connecting...');

/*
// THE WRONG WAY OF USING mongoose WITH connect-mongodb.
// The source below was the source of the problem.

mongoose.connect(mongourl, function(err) {
  console.log('THIS IS NOT PRINTED.');
  if (err) {
    console.log('THIS IS NOT PRINTED EITHER.');
    throw err;
  }
});

new mongoStore({
  db: mongoose.connection.db
}, function(err) {
  // The line below usually prints 2.
  console.log('MongoDB: readyState %d (2 = connecting, 1 = connected)', mongoose.connection.readyState);
  return console.log(err || 'connect-mongodb setup ok');
})
*/

// THE RIGHT WAY OF USING mongoose WITH connect-mongodb.
mongoose.connect(mongourl, {auto_reconnect: true, native_parser: true}, function(err) {
  new mongoStore({
    db: mongoose.connection.db
  }, function(err) {
    // The line below usuall prints 1.
    console.log('MongoDB: readyState %d (2 = connecting, 1 = connected)', mongoose.connection.readyState);
    return console.log(err || 'connect-mongodb setup ok');
  });
});

console.log('MongoDB: connected.')

Schema = mongoose.Schema;

attributes = {
  email: {
    type: String,
    required: true,
    unique: true
  }
};

var schema = new Schema(attributes);

var User = mongoose.model('User', schema);

function createUser(callback) {

  var userPropertiesDict = {
    email: 'some.email@example.com',
  }

  console.log('Calling User.create...');
  User.create(userPropertiesDict, callback);
}

function NEVER_CALLED_CALLBACK(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', _)
    }
}

createUser(NEVER_CALLED_CALLBACK); // This either creates new User or logs an error that it already exists.

另请参阅帮助我以正确方式解决问题的这篇文章。

于 2013-05-22T06:00:43.173 回答