![](/img/trans.png)
[英]how to add last login date in application using nodejs and mongodb?
[英]Keep track of last login date with NodeJS and MongoDB
我正在為我的 Node 應用程序添加最后登錄功能,但似乎無法讓它工作。 以下是我為 mongoose user
架構提供的內容:
userSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: String,
email: {
type: String,
unique: true
},
avatar: String,
firstName: String,
lastName: String,
lastLogin: {
type: Date,
default: Date.now
},
resetPasswordToken: String,
resetPasswordExpires: Date,
isAdmin: {
type: Boolean,
default: false
}
});
userSchema.plugin(passportLocalMongoose);
userSchema.statics.newLogin = function login(id, callback) {
return this.findByIdAndUpdate(id,{'$set' : { 'lastLogin' : Date.now()} }, { new : true }, callback);
};
module.exports = mongoose.model("User", userSchema);
這是我的登錄路線:
router.post("/login", passport.authenticate("local",
{
failureRedirect: "/login"
}), function(req, res) {
User.findOneAndUpdate(req.username, {lastLogin: Date.now()}, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
});
我已經能夠在創建帳戶時獲得初始日期; 但是,當我使用同一個帳戶登錄時,日期保持不變。 我在這里想念什么?
還有一些其他類似主題的問題,但似乎沒有一個可以解決我的問題。 具體來說, 這個問題我已經實施了部分解決方案無濟於事。 在此先感謝您的幫助!
這是當前正在測試的代碼,例如 req.body:
{ username: 'anyUserHere', password: 'anyPasswordHere' }
請求用戶:
{
isAdmin: true,
_id: 5e9b301a6bb78973c9ec8fae,
username: 'anyUserHere',
salt: 'saltValue',
hash: 'hashValue',
__v: 0,
avatar: '../images/admin.jpg',
email: 'example@example.com',
firstName: 'first',
lastName: 'last',
password: 'anyPasswordHere',
lastLogin: 2020-05-22T18:35:50.941Z
}
因此,在這種情況下,“anyUserHere”示例應該是正在更新的示例,但更新發生在 Mongo 中的第一個用戶身上。 控制台 output:
Successfully updated the lastLogin {
isAdmin: false,
_id: 5e939f988ced3e0428c8b521,
username: 'test',
__v: 0,
lastLogin: 2020-05-22T18:38:59.836Z
}
你能更新User.newLogin();
使用以下代碼並嘗試
User.newLogin(id, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
});
router.post("/login", passport.authenticate("local",
{
failureRedirect: "/login"
}), function(req, res) {
User.newLogin(id, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
});
編輯
根據當前使用findOneAndUpdate
的方法,您需要對filter
進行以下更新
User.findOneAndUpdate({username: req.username}, {lastLogin: Date.now()}, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.