Im using Typeorm (v8.0.2) and Nestjs(v8) with Nodejs(v16). My problem is when I create a book Typeorm doesn't return generated book id
Here is Book.entity
@Entity()
export class Book {
@PrimaryGeneratedColumn('increment')
id: number;
@Column()
title: string;
@Column()
author: string;
}
And this is book.service
async createBook(createBookDto: CreateBookDto): Promise<Book> {
const book = await this.bookRepository.create(createBookDto)
await this.bookRepository.save(createBookDto)
return book
}
and when I use postman and create a Book it just returns
{
title: "example"
author: "foo"
}
id of generated book is missing
TL;DR: return result of this.bookRepository.save(createBookDto)
, not this.bookRepository.create(createBookDto)
From the docs:
create
- Creates a new instance of User
. Optionally accepts an object literal with user properties which will be written into newly created user object.
const user = repository.create(); // same as const user = new User();
const user = repository.create({
id: 1,
firstName: "Timber",
lastName: "Saw"
}); // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
In your example you are using @PrimaryGeneratedColumn()
decorator that uses database level auto-increment function. The value of this column will be generated after the save()
method, not after create()
.
What happened in my case was that a developer defined id
in the entity file with a @PrimaryColumn
decorator rather than a @PrimaryGeneratedColumn
decorator, and nest was not returning the id
after save()
.
It must be @PrimaryGeneratedColumn
. e.g.,
@PrimaryGeneratedColumn({ name:'id', type:'bigint' }) id !: number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With