How to update user lastlogin time in react

Viewed 21

i want to display last login time of user in table column after they logged in. i tried with some code in backend with nodejs and mongoose but sure it is not the right way. Can anyone help me how to handle it from backend and FE as well?

Here is Schema of user:

const userSchema = new Schema(
  {
    name: { type: String },
    email: { type: String, unique: true},
    password: { type: String },
    status: {type: String, enum:["Active", "Blocked"], default:"Active"},
    token: { type: String },
    lastLogin: { type: Date, default: Date.now()},
  },
  { timestamps: true }
);  

Route:

userRouter.post("/login", async (req, res, next) => {
  try {
    const { email, password } = req.body;
    if (!(email && password)) res.status(204).send({ msg: "All fields are required!" });
    const user = await UsersModel.findOne({ email });
    console.log(user);
    if (user && (await bcrypt.compare(password, user.password))) {
      const accessToken = await JWTAuthenticate(user);
      user.token = accessToken;
      user.lastLogin = Date.now()
      res.status(200).send(user);
    } else {
      res.status(404).send({ msg: "User with this email not found!" });
    }

    UsersModel.findOneAndUpdate({lastLogin: Date.now()}, (err, data) => {
      if(err) console.log(err);
      else console.log("Successfully updated the lastLogin", data);
    })
  } catch (error) {
    next(error);
  }
});
1 Answers

You just have to call await user.save() after setting lastLogin (and remove findOneAndUpdate call)

or

actually query for the user in your findOneAndUpdate call. Currently you are querying for a 'lastLogin' field with the value now() which will never match. Adjust this call as following:

UsersModel.findByIdAndUpdate(user._id, {lastLogin: Date.now()}, (err, data) => {
      if(err) console.log(err);
      else console.log("Successfully updated the lastLogin", data);
})

Just a hint: JWTs are used for storing the session state on client side. You don't need to actually store these Tokens in your database. You just have to validate it on incoming request.

Related