mongoose用户定义的方法

时间:2015-09-08 21:10:52

标签: node.js mongodb mongoose

我在尝试向我的架构添加实例方法时遇到了麻烦。

以下是一个例子:

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

然后在其他地方的代码中,我尝试调用其中一种方法:

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('goofy@goober.com');

然后我得到以下错误(stacktrace省略):

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

我不能为我的生活弄清楚这一点.. 我正在使用猫鼬3.8。我知道我做错了什么,但我需要另一个更智能,更有经验的眼睛来帮助我找到它。

我也试过定义这样的方法:

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

但它似乎并不重要。

这样的帖子只有一个,我可以在堆栈溢出时找到,他们通过确保在调用mongoose.model(' name',schema)之前定义了他们的方法来解决他们的错误。我之前已经定义了它们,所以我不认为它是同一个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题在于Users.find为您提供了数组。

所以,要么:

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

或:

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