问题
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.
回答1:
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);
});
});
回答2:
It looks like in your res.redirect you're trying to construct a URL by concatenating an object to a string. I doubt that will have the result you want. What do you expect the URL to look like?
来源:https://stackoverflow.com/questions/10989343/passport-js-and-mongoose-js-populate-user-on-login-loses-populated-field-on-re