11

在过去的一个小时里,我一直在尝试使用 findOne、findOneOrCreate 等方法为 passport.js 编写用户模块,但无法正确完成。

用户.js

var User = function(db) {
  this.db = db;
}

User.prototype.findOne(email, password, fn) {
  // some code here
}

module.exports = exports = User;

应用程序.js

User = require('./lib/User')(db);
User.findOne(email, pw, callback);

我经历了几十个错误,主要是

TypeError: object is not a function

或者

TypeError: Object function () {
  function User(db) {
    console.log(db);
  }
} has no method 'findOne'

如何在不创建用户对象/实例的情况下创建具有这些功能的适当模块?

更新

我浏览了建议的解决方案:

var db;
function User(db) {
  this.db = db;
}
User.prototype.init = function(db) {
  return new User(db);
}
User.prototype.findOne = function(profile, fn) {}
module.exports = User;

没运气。

TypeError: Object function User(db) {
  this.db = db;
} has no method 'init'
4

2 回答 2

16

这里发生了几件事,我已经更正了您的源代码并添加了注释以进行解释:

库/用户.js

// much more concise declaration
function User(db) {
    this.db = db;
}

// You need to assign a new function here
User.prototype.findOne = function (email, password, fn) {
    // some code here
}

// no need to overwrite `exports` ... since you're replacing `module.exports` itself
module.exports = User;

应用程序.js

// don't forget `var`
// also don't call the require as a function, it's the class "declaration" you use to create new instances
var User = require('./lib/User');

// create a new instance of the user "class"
var user = new User(db);

// call findOne as an instance method
user.findOne(email, pw, callback);
于 2012-08-02T18:36:46.697 回答
6

你需要new User(db)在某个时候。

你可以做一个init方法

exports.init = function(db){
  return new User(db)
}

然后从您的代码中:

var User = require(...).init(db);
于 2012-08-02T17:13:57.010 回答