hagopj13 / node-express-boilerplate

A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose
MIT License
6.99k stars 2.05k forks source link

Mongoose V5.5.3+ introduced .remove() deprecation #281

Open JellyPies opened 11 months ago

JellyPies commented 11 months ago

PROBLEM As of Mongoose V5.5.3+, use of the .remove() function on documents was deprecated, and should no longer be used, it will throw an error for a non-existent function.

ERROR ERROR: POST /v1/auth/logout 500 - 43.461 ms - message: refreshTokenDoc.remove is not a function

FIX Anyone updating their mongoose with this project should use .deleteOne() instead. This project utilizes the deprecated .remove() in two locations within auth.service.js, and one location in the user.service.js

auth.service.js LINES 27 - 33

const logout = async (refreshToken) => {
  const refreshTokenDoc = await Token.findOne({ token: refreshToken, type: tokenTypes.REFRESH, blacklisted: false });
  if (!refreshTokenDoc) {
    throw new ApiError(httpStatus.NOT_FOUND, 'Not found');
  }
  await refreshTokenDoc.remove(); // DEPRECATED, REPLACE WITH await refreshTokenDoc.deleteOne();
};

auth.service.js LINES 40 - 52

const refreshAuth = async (refreshToken) => {
  try {
    const refreshTokenDoc = await tokenService.verifyToken(refreshToken, tokenTypes.REFRESH);
    const user = await userService.getUserById(refreshTokenDoc.user);
    if (!user) {
      throw new Error();
    }
    await refreshTokenDoc.remove(); // DEPRECATED, REPLACE WITH await refreshTokenDoc.deleteOne();
    return tokenService.generateAuthTokens(user);
  } catch (error) {
    throw new ApiError(httpStatus.UNAUTHORIZED, 'Please authenticate');
  }
};

user.service.js LINES 73 - 80

const deleteUserById = async (userId) => {
  const user = await getUserById(userId);
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
  }
  await user.remove(); // DEPRECATED, REPLACE WITH await user.deleteOne();
  return user;
};