将变量传递给路由

时间:2012-08-27 06:25:47

标签: node.js express mongoose

我正在尝试将一些变量传递到我的路线中,但似乎无法正确使用它。我有这个内容的db.js:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dowhat');

/**
 * Schema definitions.
 */
var User = new Schema({
    name : { type : String, required : true }
  , pass : { type : String, required : true }
});

var List = new Schema({
    _from       : { type : Schema.Types.ObjectId, ref : 'User' }
  , _to         : { type : Schema.Types.ObjectId, ref : 'User' }
  , title       : String
  , description : String
  , created     : { type : Date, default              : Date.now }
  , updated     : { type : Date, default              : Date.now }
});

exports.users = mongoose.model('User', User);
exports.lists = mongoose.model('List', List);

我的app.js上有这个:

app.use(function(req, res, next) {
  db.users.findOne({ name : 'foo' }, '_id', function(err, user) {
    req.session.user = user._id;
  });

  next();
});
当我尝试使用routes / index.js时,

req.session.userundefined

exports.index = function(req, res) {
  console.log(req.session.user);
  res.render('index');
}

我还尝试将req.session.user替换为res.locals.user,但在routes / index.js上仍为undefined

1 个答案:

答案 0 :(得分:0)

因为在调用db.users.findOne的回调之前调用了next()。

在回调中移动下一步。

var db = require('./db'); // Make sure you're including me ;D

app.use(function(req, res, next) {
  db.users.findOne({ name : 'foo' }, '_id', function(err, user) {
    req.session.user = user._id;
    next();
  });
});