Class methods in node.js


Question

I've been trying for the last hour to write a user module for passport.js with the findOne, findOneOrCreate, etc. methods, but can't get it right.

User.js

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

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

module.exports = exports = User;

app.js

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

I've been through dozens of errors, mostly

TypeError: object is not a function

or

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

How do I create a proper module with these functions without creating an object/instance of User?

Update

I went over the proposed solutions:

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;

No luck.

TypeError: Object function User(db) {
  this.db = db;
} has no method 'init'
1
11
8/3/2012 6:27:52 AM

Accepted Answer

A couple of things are going on here, I've corrected your source code and added comments to explain along the way:

lib/User.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;

app.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);
16
8/2/2012 6:36:46 PM

You need to new User(db) at some point.

You could make an init method

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

And then from your code:

var User = require(...).init(db);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon