I am new to typeORM and I am making a basic CRUD API using the Active-record pattern.
I have a very basic entity and to save it to the database I use the following code:
const newUser = User.create(request.body)
But when I try to compile, User.create returns an User[] object instead of User.
If I call manually the method using the object, like User.create({username: request.body.username, ... })
I get successully an User
, but when I use request.body
I always get an User[]
regardless if I use the exact same object as the body of my request.
I checked the documentation and User.create
in fact has a override that returns a single User, if an object-like parameter is passed, but produces a User[]
if an array-like parameter is passed.
I've tried many thigs, like destructuring User.create({... request.body})
and similar, but it does not work.
I think this is very confusing and prone to error, as User.create
will behave differently using objects and the bodys request.
Does something like User.createOne() or something like that exist? so I can force the behavior to always create one single object? I've not found anything.
You can force it by casting the request body to an object first
const newUser = User.create(request.body) // User[]
const newUser = User.create(request.body as Object) // User