In this code, passportjs cannot find the path to the database with logins and passwords. How can you set the right path?

var express = require('express'); var app = express(); var cookieParser = require('cookie-parser'); var jade = require('jade'); var bodyParser = require('body-parser'); var session = require('express-session'); var mongoose = require('mongoose'); var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }); } )); app.set('view engine', 'jade'); app.use(bodyParser()); app.use(cookieParser("megaultrasupersecret")); app.use(session({secret: 'my secret'})); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); app.use(passport.initialize()); app.use(passport.session()); mongoose.connect('mongodb://localhost/db'); var User = mongoose.model('User', { username: String, password: String, age: Number }); app.get('/', function(req, res){ res.render('index'); }); app.get('/registr', function(req, res){ res.render('registr'); }); app.get('/logged', function(req, res){ if (req.cookies.cookie) { res.render('logged'); } else { res.redirect('/'); } }); app.post('/registr', function (req, res, next) { new User({ username: req.body.username, password: req.body.password, age: req.body.age }).save(function (err) { if (err) console.log(err); }); res.redirect('/') }); app.post('/logged', passport.authenticate('local', { successRedirect: '/logged', failureRedirect: '/login', })); app.post('/exit', function(req, res) { res.clearCookie('cookie', 1337); res.redirect('/'); }); app.listen(3000, function() { console.log('"http://localhost:3000"'); }); 

    1 answer 1

    It would not be superfluous to add in the question what error you catch, but I will try telepathically.

    1. Try swapping a piece with mongoose.connect and creating a model with a piece, where passport.serialize( ... ... app.use(passport.session)

    2. check if your mongo is running and you don’t have a firewall / firewall / others anywhere. Do you get connected to mongo with the help of some utility (Robomongo for example)?

    3. check under what user your obd is available, probably you need to add something like mongodb://username:password@localhost/db in the connection string. You probably have a standard port, but you should also check it out.

    4. And finally, I see familiar rakes - use the same secret for cookieParser and bodyParser, otherwise your session will sometimes be buggy.