0
votes

I struggle with TypeORM & MongoDB. I used this library since several months now but I have an uncommon problem.

When I save an entity, sometimes my data is updated, sometimes not. The exact same request won't work the first time but will the second time. I use save() for updating and inserting. Everything is fine on insertion.

Here is my code (TypeORM with NestJS) :

==> Entity

@Entity()
export class User {
  @ObjectIdColumn()
  @Type(() => String)
  id: ObjectID;

  @Column()
  address: string;
}

==> DTO

export class UpdateUserDto {
  @IsNotEmpty({ message: () => translate('validation.is_not_empty') })
  address: string;
}

==> Controller

@Put(':userId')
@Authentified()
async update(@Param('userId') userId, @Body() dto: UpdateUserDto) {
  return await this.usersService.update(userId, dto);
}

==> usersService :

import { MongoRepository } from 'typeorm';
...
private readonly userRepository: MongoRepository<User>
...
async update(userId: string, dto: UpdateUserDto): Promise<User> {
   const user = await this.userRepository.findOneOrFail(userId);
   user.address = dto.address;

   return await this.userRepository.save(user);
}

When I find() after the save(), my user address is not updated whereas I received modifiedCount 1 from Mongo. If I repeat the request, this time it is working...

Any ideas ?

1

1 Answers

1
votes

I finally got it, several months later...

In my NodeJS Auth middleware I was logging a timestamp to store the last time user connects to the API. It means I was using save() twice : in the middleware and in my service ! Sometimes it was working because saving the timestamp was quick enough to let my service save the update, sometimes not. Instead of using save() I use updateOne() with $set, no more concurrence problem.

I answer my own question, hope this helps for others !