猫鼬-nodejs-由于某种原因没有方法
有一些问题!
错误是
local:
{ password: '$2a$08$kSflSzcciqWN78nfqAu/4.ZBZaXkqb19bEypeWcuSxg89yPNuijYO',
email: '***@gmail.com' } } has no method 'usersCharacters'
但是它确实有方法! 我不确定它是否可以正确导出.据我所知,我在执行此操作的方式与用户使用的其他方法类似,只是在这里似乎不起作用.
But it does have the method! I am not sure it is being exported properly. As far as I can tell I am doing it similarly to the other methods users have except here it doesn't seem to work.
user.js模型文件
user.js model file
....
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
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
});
这是要点,其中包含我的更多模型文件代码:
here is a gist with more of my model file code:
从中创建User
模型后添加到UserSchema
的方法,在
Methods that you add to UserSchema
after creating the User
model from it, won't be available on User
model instances.
因此,在创建User
模型之前创建方法:
So create the method before creating the User
model:
UserSchema.methods.usersCharacters = function(email,cb){ ... };
var User = mongoose.model('User', UserSchema);
module.exports = User;
在相关说明中,只有对mongoose.model('User', UserSchema)
的第一次调用会处理该架构以创建'User'
模型.随后的调用将忽略UserSchema
参数并返回现有模型.
On a related note, only the first call to mongoose.model('User', UserSchema)
processes the schema to create the 'User'
model. Subsequent calls ignore the UserSchema
parameter and return the existing model.