TypeORM MongoDB 存储库不会每次都保存

TypeORM MongoDB repository won't save every time

我与 TypeORM 和 MongoDB 斗争。几个月以来我一直在使用这个库,但我遇到了一个不常见的问题。

当我保存实体时,有时我的数据会更新,有时不会。完全相同的请求第一次不会起作用,但第二次会起作用。我使用 save() 进行更新和插入。插入时一切正常。

这是我的代码(带有 NestJS 的 TypeORM):

==> 实体

@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;
}

==> 控制器

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

==> 用户服务:

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);
}

当我在 save() 之后找到 () 时,我的用户地址没有更新,而我从 Mongo. 收到了 modifiedCount 1 如果我重复请求,这次它正在工作...

有什么想法吗?

我终于明白了,几个月后...

在我的 NodeJS Auth 中间件中,我记录了一个时间戳以存储用户最后一次连接到 API。这意味着我使用了 save() 两次:在中间件和我的服务中!有时它可以工作,因为保存时间戳的速度足以让我的服务保存更新,有时则不能。我没有使用 save(),而是使用带有 $set 的 updateOne(),不再有并发问题。

我回答我自己的问题,希望这对其他人有帮助!