使用Mongoose.js,我的身份驗證方法填充字段「companyRoles._company」,但填充的數據會在返回公司參考ID時恢復爲公司參考ID我嘗試訪問我的req.user對象中相同的填充字段。Passport.js和Mongoose.js在登錄時填充用戶 - 在req.user上丟失填充字段
//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);
});
req.logIn後,登錄req.user顯示 - companyRoles {_公司:[對象]}
但是,當我重定向到/公司/:ID航線登錄後,它顯示了ID,而不是人口稠密[對象] - companyRoles {_公司:4fbe8b2513e90be8280001a5}
任何想法,爲何現場不保持填充?謝謝。
感謝ebohlman,你是正確的。我沒有更新從我以前沒有填充_company對象的重定向url。我更新了代碼,現在有_company._id。 –
雖然,問題依然存在。在/ companies/{companyId}中,req.user.companyRoles [i] ._ company是ObjectID而不是填充的_company對象(名稱,ID等)。這很奇怪,因爲在req.logIn回調中記錄它時,req.user是一個填充對象。 –
我認爲你需要顯示處理'/ companies /:companyId'的代碼。請記住,在重定向之後,瀏覽器將發出一個全新的請求,並且您在原始'req'對象上設置的任何屬性都不會自動出現在新請求上。 – ebohlman