How to update current time on knex.js

x·2022년 6월 28일
0

user migration file

import { Knex } from 'knex';

export async function up(knex: Knex): Promise<void> {
  const result = await knex.schema.createTable('users', (table) => {
    table.bigIncrements('id');
    table.string('email', 50).nullable();
    table.timestamp('created_at').defaultTo(knex.fn.now());
    table.timestamp('updated_at').defaultTo(knex.fn.now());
  });
  console.log(result);
}

export async function down(knex: Knex): Promise<void> {
  await knex.schema.dropTable('users');
}

use this.knex.fn.now() when update column

async updateUser(userId: number, email: string) {
  try {
    const result: number = await this.knex('users')
    .where({ id: userId })
    .update(
      {
        email,
        updated_at: this.knex.fn.now(),
      },
      ['id']
    );
    console.log(`updateUser result ${JSON.stringify(result)}`);
    return result;
  } catch (error) {
    console.error(error);
    return false;
  }
}

0개의 댓글