You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM getMongoManager updateOne执行$push时遇类型错误:string无法赋值给never

解决TypeORM中$push操作的TypeScript类型错误

问题场景

在NestJS项目中,使用TypeORM的getMongoManager().updateOne方法对MyEntity模型中string[]类型的favorite字段执行$push操作添加productId时,触发TypeScript类型错误。

MyEntity.service.ts 代码

import { getMongoManager, MongoRepository, Repository } from 'typeorm';
import MyEntity from './entities/myEtity.model';
import { Logger } from '@nestjs/common';

...

export class MyEntityService{
  constructor(
    @InjectRepository(MyEntity)
     private MyEntityRepository: MongoRepository<MyEntity>,
  ) {}

  async addFavoriteProduct(myId: string, productId: string) {
    const manager = getMongoManager();
    try {
      await manager.updateOne(
        MyEntity,
        { id: myId },
        { $push: { favorite: productId } },
      );
    } catch (err) {
      Logger.error(`Failed to add product `);
    }
  }
}

MyEntity.model.ts 代码

import { Column, Entity } from 'typeorm';

@Entity()
export default class MyEntity  {
  @Column()
  id: string;

  ...

  @Column({ default: [] })
  favorite?: string[];
}

错误信息

Type 'string' is not assignable to type 'never'.

146         { $push: { favorite: productId } },

依赖版本:@nestjs/typeorm@^10.0.0、mongodb@4.1、typeorm@^0.3.17

解决方案

方法1:使用MongoRepository的updateOne方法

既然已经注入了MongoRepository,直接调用它的updateOne方法可以自动继承实体的类型定义,避免类型不匹配:

async addFavoriteProduct(myId: string, productId: string) {
  try {
    await this.MyEntityRepository.updateOne(
      { id: myId },
      { $push: { favorite: productId } },
    );
  } catch (err) {
    Logger.error(`Failed to add product `);
  }
}

方法2:显式指定更新对象的类型

如果必须使用getMongoManager,可以通过类型断言解决类型检测问题:

await manager.updateOne(
  MyEntity,
  { id: myId },
  { $push: { favorite: productId } } as any,
);

或者更安全的类型推导:

const updatePayload = { $push: { favorite: productId } } as Parameters<typeof manager.updateOne>[2];
await manager.updateOne(MyEntity, { id: myId }, updatePayload);

方法3:优化实体字段的类型定义

显式指定列类型为simple-array,让TypeORM更准确地识别数组类型,提升与MongoDB操作的兼容性:

@Column('simple-array', { default: [] })
favorite?: string[];

内容的提问来源于stack exchange,提问作者Sadaf Sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:58:30