如何找出passport / node js中的last_login_date
我已经创build了一个程序,使用节点js,护照,快递和mongo,首先你必须注册一个用户,然后你将能够login。 这是我的用户模式的样子:
var UserSchema = mongoose.Schema({ username: { type: String, required: true, unique: true, index: true }, password: { required: true, type: String }, creation_date: { type: Date, default: Date.now }, last_login_date: { type: Date, default: Date.now } })
如何找出用户上次login的时间? 我一直试图找出这一点,因为我认为这将需要发生在路线? 这是我的用户login路线:
router.post('/login', passport.authenticate('local'), function(req, res) { res.json('Welcome ' + req.user.username); });
有没有人设法为每个用户添加last_login_date?
任何线索都会有帮助!
如果你已经使用Mongoose,为什么不在你的模式中定义一个新的静态目的就是为了login。
这样你把你的代码保存在一起。
另外..我知道在顶层的Mongoose把findOneAndUpdate方法中的更新查询视为$ set操作,所以不需要做这样的事情
query = { $set : { 'last_login_date' : Date.now() } }
..但是…我强烈build议你仍然使用$ set操作来保持清楚,如果你切换到另一个驱动程序或插件的时间,你仍然可以保持你所有的查询。 但这只是个人的习惯。 如果你使用Mongo Shell,如果你忘记在你的更新中使用$ set,你会得到不想要的结果。
所以我build议你在用户模式中定义一个静态设置最后的logindate,并返回更新的文档,以便每次用户login时都可以在护照中使用它。
你的模式看起来像这样:
var UserSchema = mongoose.Schema({ username: { type: String, required: true, unique: true, index: true }, password: { required: true, type: String }, creation_date: { type: Date, default: Date.now }, last_login_date: { type: Date, default: Date.now } }); UserSchema.statics.login = function login(id, callback) { return this.findByIdAndUpdate(id, { $set : { 'last_login_date' : Date.now() }, { new : true }, callback); };
使用这种方法,您可以在会话中获取用户,并立即更新last_login_date。
我也build议你把这个方法放在像Ankit Ranabuild议的反序列化用户方法中。 这样你的req.user对象包含更新的last_login_date。
在您发布的代码中,您只需更新last_login_date,但不返回更新的文档。 因此,在req.user中,您仍然拥有前一个会话的last_login_date。 您可以通过将其打印到控制台来进行检查。
console.log(req.user.last_login_date); //last_login_date will not be updated res.json('Welcome ' + req.user.username);
所以从passport.authenticate方法中删除所有的更新方法
router.post('/login', passport.authenticate('local'), function(req, res) { // if login is successfull, the following message will be displayed res.json('Welcome ' + req.user.username);
并将您的passport.deserializeUser方法更改为此
passport.deserializeUser(function(id, done) { User.login(id, function(err, user) { if(err) return done(err, null); done(err, user); }); });
尝试一下,让我知道如果有什么不工作或不清楚
好的,所以我设法做到这一点,做到以下几点:
当用户login时,您查找该用户,然后更新last_login_time。 喜欢这个:
router.post('/login', passport.authenticate('local'), function(req, res) { var query = { 'username': req.user.username }; var update = { last_login_date: Date.now() }; var options = { new: true }; User.findOneAndUpdate(query, update, options, function(err, user) { if (err) { console.log(err); } }); // if login is successfull, the following message will be displayed res.json('Welcome ' + req.user.username);
这工作完美,每次用户loginlast_login_date被更新。
这是您可以获取用户并获取上次logindate的地方,手动添加用户对象。 和财产,你可以很容易地通过req.user.last_login_date访问
passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { if(err) return done(err, user); user.last_login_date = Date.now(); // Typo was here. done(err, user); }); });