fliz
fliz

Reputation: 71

mongoose user defined methods

I'm having trouble trying to add instance methods to my schemas.

Here is an example:

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

var schema = new mongoose.Schema ({
    first_name: {type: String, required: true, trim: true},
    last_name:  {type: String, required: true, trim: true},
    email:      {type: String, required: true, unique: true, dropDups: true, trim:true},
    hash:       {type: String, required: true}
});

schema.methods = {
    encrypt: function(pwd) {
         if (!pwd) return '';
         else return bcrypt.hashSync(pwd, bcrypt.genSaltSync(10));
    },
    test: function(logentry) {
         console.log(this.email + ': ' + logentry);
    }
};

mongoose.model('Users', schema);

And then in my code elsewhere I try to call one of the methods:

var mongoose = require('mongoose');
var Users = mongoose.model('Users');

function testFunction(email) {
    Users.find({email:email}, function(error, user) {
        user.test('Trying to make mongoose instance methods work.');
    });
}
testFunction('[email protected]');

And then I get the following error (stacktrace omitted):

        user.test('Trying to make mongoose instance methods work.');
             ^
TypeError: undefined is not a function

I cannot for the life of me figure this out.. I am using mongoose 3.8. I know I'm doing something wrong, but I need another, much smarter and experienced pair of eyes to help me find it.

I've tried defining the methods like this too:

schema.methods.encrypt = function(pwd) {...};
schema.methods.test = function(logentry) {...};

But it doesn't seem to matter.

There was only one previous post like this that I could find on stack overflow and they resolved their error by making sure that their methods were defined before they called mongoose.model('name', schema). I've got them defined before, so I don't think it's the same problem. Any help would be much appreciated.

Upvotes: 0

Views: 265

Answers (1)

StickyCube
StickyCube

Reputation: 1721

The problem is that Users.find gives you an array.

So, either:

Users.find({ email: email }, function (e, users) {
    users[0].test('foo bar whatever');
});

or:

Users.findOne({ email: email }, function (e, user) {
    user.test('foo bar whatever');
});

Upvotes: 1

Related Questions