2014-10-31 79 views
0

有一些问题!mongoose - nodejs - 由于某种原因没有方法

的错误是

local: 
    { password: '$2a$08$kSflSzcciqWN78nfqAu/4.ZBZaXkqb19bEypeWcuSxg89yPNuijYO', 
    email: '***@gmail.com' } } has no method 'usersCharacters' 

但它确实有方法! 我不确定它是否正确导出。据我所知,我正在做类似于用户拥有的其他方法,除了这里它似乎并没有工作。

user.js的模型文件

.... 
module.exports = mongoose.model('User', UserSchema); 

var User = mongoose.model('User', UserSchema); 


/* method works :D ! -- not sure if over complicated though! */ 
UserSchema.methods.usersCharacters = function(email,cb){ 
    User.findOne({'local.email' : email }).exec(function(err, user){ 
    if (err) console.log("shit"); 
    var _return = []; 

    user.characters.forEach(function(err, i){ 
     Character.findOne({ "_id" :user.characters[i] }).exec(function(err2, dude){ 
     _return.push(dude); 

     /* Can't think of a smarter way to return :(*/ 
     if (i == user.characters.length-1) 
      cb(_return); 
     }); 
    }); 
    }); 
}; 

routes.js

/* This doesn't work! I am wondering how I might be able to return this users characters -- 
* 
* The error is here btw! TypeError: Cannot call method 'usersCharacters' of undefined -- line with character : **** 
*/ 
app.get('/profile', isLoggedIn, function(req, res) { 
    var mongoose = require('mongoose'); 
    var UserSchema = mongoose.model('User', UserSchema); 
    console.log(UserSchema); 
    // ERROR ON THIS LINE! : (
    characters : req.user.usersCharacters(req.user.email, function(_characters){ 
        console.log("list of characters: " + _characters); 
        return _characters; 
        res.render('profile.ejs', { 
        user : req.user, // get the user out of session and pass to template 
        characters : characters 
        }); 

这里有更多的我的模型文件的代码要点:

https://gist.github.com/hassanshaikley/d4766251ec53feec8e84

回答

1

方法,您后加UserSchema 从它创建User模型,将不会在User模型实例上可用。

创建User模型之前,因此,创建方法:

UserSchema.methods.usersCharacters = function(email,cb){ ... }; 

var User = mongoose.model('User', UserSchema); 
module.exports = User; 

在一个相关的说明,只mongoose.model('User', UserSchema)第一个呼叫处理架构创建'User'模型。后续调用忽略UserSchema参数并返回现有模型。

相关问题