Search code examples
node.jsexpressknex.jsobjection.js

.patch() do not saves the parameter to the database in Objection.js with Knex


I am creating Express API and I am using Objection.js as ORM with Knex.js I have created router for updating user password from the profile with 2 fields (old password and the new password),first it verifies the old password (protection from stealing JWT token). After it returns valid condition then I proceed to hash the new password with bcrypt and update it with .patch() otherwise it will return validation error the old password it is not the correct password. The problem is when I send the same exact request it goes through meaning that .patch not worked and did not save the new password to the database. Can anyone explain some solution to this problem or probably hit me with some documention on how to fix it The code is bellow:

router.patch('/updatepassword', async (req, res, next) => {
  const { id } = req.user;
  const {
    oldPassword,
    newPassword,
  } = req.body;
  try {
    await passwordSchema.validate({
      oldPassword,
      newPassword,
    }, {
      abortEarly: false
    });
    const UserOldPassword = await User.query().select('password').findById(id);
    const validOldPassword = await bcrypt.compare(oldPassword, UserOldPassword.password);
    if (validOldPassword) {
      const hashedPassword = await bcrypt.hash(newPassword, 12);
      const defi = User.query().patch({ password: hashedPassword }).where('id', id).returning('*')
        .first();
      console.log(defi);
      res.status(200).json({
        message: returnMessage.passwordUpdated
      });
    } else {
      const error = new Error(returnMessage.invalidOldPassword);
      res.status(403);
      throw error;
    }
  } catch (error) {
    next(error);
  }
});

Console log:

QueryBuilder {
  _modelClass: [Function: User],
  _operations: [
    UpdateOperation {
      name: 'patch',
      opt: [Object],
      adderHookName: null,
      parentOperation: null,
      childOperations: [],
      model: [User],
      modelOptions: [Object]
    },
    KnexOperation {
      name: 'where',
      opt: {},
      adderHookName: null,
      parentOperation: null,
      childOperations: [],
      args: [Array]
    },
    ReturningOperation {
      name: 'returning',
      opt: {},
      adderHookName: null,
      parentOperation: null,
      childOperations: [],
      args: [Array]
    },
    FirstOperation {
      name: 'first',
      opt: {},
      adderHookName: null,
      parentOperation: null,
      childOperations: []
    }
  ],
  _context: QueryBuilderContext {
    userContext: QueryBuilderUserContext { [Symbol()]: [Circular] },
    options: InternalOptions {
      skipUndefined: false,
      keepImplicitJoinProps: false,
      isInternalQuery: false,
      debug: false
    },
    knex: null,
    aliasMap: null,
    tableMap: null,
    runBefore: [],
    runAfter: [],
    onBuild: []
  },
  _parentQuery: null,
  _isPartialQuery: false,
  _activeOperations: [],
  _resultModelClass: null,
  _explicitRejectValue: null,
  _explicitResolveValue: null,
  _modifiers: {},
  _allowedGraphExpression: null,
  _findOperationOptions: {},
  _relatedQueryFor: null,
  _findOperationFactory: [Function: findOperationFactory],
  _insertOperationFactory: [Function: insertOperationFactory],
  _updateOperationFactory: [Function: updateOperationFactory],
  _patchOperationFactory: [Function: patchOperationFactory],
  _relateOperationFactory: [Function: relateOperationFactory],
  _unrelateOperationFactory: [Function: unrelateOperationFactory],
  _deleteOperationFactory: [Function: deleteOperationFactory]
}
PATCH /v1/profile/updatepassword 200 1346.797 ms - 42

Solution

  • Solution: Do not forget to put await on async function.