Passport.js and Mongoose.js fill the user at login - they lose the filled field on req.user

Using Mongoose.js, my authentication method populates the companyRoles._company field, but the populated data returns to the company link identifier 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, the req.user log shows - companyRoles {_company: [Object]}

But when I redirect the route / companies /: id after login, it shows the identifier, not the filled [object] - companyRoles {_company: 4fbe8b2513e90be8280001a5}

Any ideas as to why the field does not remain populated? Thanks.

+8
mongodb mongoose
source share
2 answers

The problem was that I did not fill in 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); }); }); 
+12
source share

It looks like in res.redirect you are trying to create a url by combining an object into a string. I doubt that you will have the result you want. What do you expect from the url?

0
source share

All Articles