Using Mongoose.js, my authenticate method populates the field "companyRoles._company," but the populated data reverts to the company reference ID when I try to access the same populated field in my req.user object.
//Authentication
UserSchema.static('authenticate', function(email, password, callback) {
this.findOne({ email: email })
.populate('companyRoles._company', ['name', '_id'])
.run(function(err, user) {
if (err) { return callback(err); }
if (!user) { return callback(null, false); }
user.verifyPassword(password, function(err, passwordCorrect) {
if (err) { return callback(err); }
if (!passwordCorrect) { return callback(null, false); }
return callback(null, user);
});
});
});
//login post
app.post('/passportlogin', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) { return res.redirect('/passportlogin') }
req.logIn(user, function(err) {
if (err) { return next(err); }
console.log('req User');
console.log(req.user);
return res.redirect('/companies/' + user.companyRoles[0]._company._id);
});
})(req, res, next);
});
app.get('/companies/:cid', function(req, res){
console.log('req.user in companies:cid');
console.log(req.user);
});
After req.logIn, logging req.user shows - companyRoles{_company: [Object]}
But when I redirect to /companies/:id route after logging in, it is showing the id and not a populated [object] - companyRoles{_company: 4fbe8b2513e90be8280001a5}
Any ideas as to why the field does not remain populated? Thanks.
The problem was that I was not populating the field in the passport.deserializeUser function, here is the updated function:
//deserialize
passport.deserializeUser(function(id, done) {
User.findById(id)
.populate('companyRoles._company', ['name', '_id'])
.run(function (err, user) {
done(err, user);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With