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

NestJS使用Mongoose的insertMany方法报is not a function如何解决

报错原因
  • insertMany 是 Mongoose 模型(Model)的静态方法,只能通过模型本身直接调用,不能通过模型实例调用。你代码中通过 new this.uploadModel() 创建的是单个 Upload 文档实例,该实例仅支持单文档相关操作方法,不存在 insertMany 方法,因此触发类型错误。
  • 额外注意:insertMany 批量插入后返回的是文档数组,原方法返回值类型 Promise<IUpload> 也需要同步修正。
正确代码(upload.service.ts 修正后)
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Injectable } from '@nestjs/common';
import { IUpload } from './upload.model';

@Injectable()
export class UploadService {

  constructor(
    @InjectModel('Upload') private readonly uploadModel: Model<IUpload>
  ) {}

  // 返回值修改为数组类型
  async create({ files, body }): Promise<IUpload[]> {
    const arr = files.map((file) => {
      return {
        name: file.filename,
        dateCreate: body.dateCreate,
        usernameCreate: body.usernameCreate,
      };
    });
    // 直接调用模型的静态insertMany方法,不需要创建实例
    return this.uploadModel.insertMany(arr);
  }
}

内容的提问来源于stack exchange,提问作者John Vasiliev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:06:07