2014-10-31 82 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參數並返回現有模型。

相關問題