WABBIT0111 WABBIT0111 - 1 month ago 15
Node.js Question

NodeJS Mongoose Passport local strategy query Mongodb gives error,

I have a Passport local strategy try to query a user in mongodb:

passport.use(new LocalStrategy(
function(username, password, done){
console.log("username and password is >>>>>", username, password);
var findOne = Q.nbind(User.findOne, User);
findOne({"username": username})
.then(function(user){
console.log("inside findone user>>>>>", err, user);

if (!user) {
return done( null, false, {messge: 'This user is not registered.'});
}

if (!user.comparePasswords(password)){
return done(null, false, {message: 'This password is not correct'});
}

return done(null, user);
})
.fail(function(err){
console.log("failed at here");
return done(null, false, {message: "Server have difficulty"});
})
}
));


"failed at here" is printed, which means there's error accessing mongodb. However, I write the very similar function in my signup function, and every thing works fine:

exports.signup = function(req, res, next){
console.log("hit the signup function");
var findOne = Q.nbind(User.findOne, User);
findOne({username: req.body.username})
.then(function(user){
console.log("user from query is >>>>>", user);
if (!user){
// user doesn't exist, create a new one\
var create = Q.nbind(User.create, User);
var newUser = {username: req.body.username, password: req.body.password};
return create(newUser);
} else {
// user already exist, redirect to sign in page
res.send(409, 'already exist');
//res.redirect('/signin');
}
})
.then(function(user){
res.json(200,user);
})
.fail(function(err){
//next(err);
console.log("error is >>>>", err);
res.redirect('/signin');
})
};


I have created a user through signup. so it will give me 409 when i try to sign up with the same user. However, when I try to sign in with that user, the passport local strategy reports error accessing mongodb. Any thoughts?
You are welcome to take a look at the repo: https://github.com/7seven7lst/chatterApp
The passport config can be found in: https://github.com/7seven7lst/chatterApp/blob/master/lib/routes.js
and the signup can be found in:
https://github.com/7seven7lst/chatterApp/blob/master/lib/controllers/user.js

Answer
.then(function(user){
  console.log("inside findone user>>>>>", err, user);

The error is being thrown because that err isn't defined.

If you log the actual error that the fail function:

.fail(function(err){
  console.log("failed at here", err);
  return done(null, false, {message: "Server have difficulty"});
})

you will see:

ReferenceError: err is not defined
    at /Users/dting/chatterApp/lib/routes.js:16:49