I have this error: TypeError: User.getUserByUsername is not a function at Strategy._verify (.../routes/users.js:65:10)
var User = require('../models/user');
passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err,user){
if(err) throw err;
if (!user){
return done(null, false, {message: 'Unknow User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null,user);
} else {
return done(null, false, {message: "Invalid password"});
}
});
});
}));
The function is defined in models/user.js
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
Check what the ../models/user
module is exporting. From your description of the problem, it exporting something, but that something doesn't have a getUserByUsername
function -- is that module perhaps exporting a prototype or class, which you should instantiate, eg:
var UserModel = require('../models/user');
var user = new UserModel();
...
From the looks of it, you're using Mongoose (always good to mention in your questions). If not, disregard the following (but please update your question to signify which ORM you're using).
I think that you might be doing this in models/user.js
:
module.exports.getUserByUsername = function(...) {}
...
module.exports = mongoose.model('User', ...);
The latter assignment will replace module.exports
, therefore making getUserByUsername
unreachable.
Instead, it's probably better to make getUserByUsername
a static method , just like comparePassword
:
userSchema.statics.getUserByUsername = function(...) {}
Try below , Change your User.js file as below:
exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
};
Could it be that you assign to the module.exports
later down the file? Exporting members should be declared after assigning to module.exports
or exports
Eg
module.exports.getUserByUsername = function() {...};
module.exports = User;
would be a common issue that resembles yours.
The issue was because of a wrong declaration of one of the function of the process flow. All the functions have to be declared the same way in order to export correctly all the object.
module.exports.getUserByUsername = function()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.