TypeORM: update item and return it
To expand on sandrooco's answer, this is what I do:
const property = await this.propertyRepository.findOne({
where: { id }
});
return this.propertyRepository.save({
...property, // existing fields
...updatePropertyDto // updated fields
});
I just found out that I can do this with the .save
method:
return this.taskRepository.save({
id: task.id,
state,
dueDate
});
According to the docs (section save
), partial updates are supported as well:
Also supports partial updating since all undefined properties are skipped.
Of note, .save
creates a new record if it doesn't exist, which may not be intended, and can sometimes be a security risk. To safeguard this, you can use .createQueryBuilder
to achieve it in 1 query:
const result = this.taskRepository.createQueryBuilder()
.update({
state,
dueDate,
})
.where({
id: task.id,
})
.returning('*')
.execute()
return result.raw[0]
Important: using the querybuilder like this is only supported by MSSQL, PostgreSQL and MariaDB.