nestjs mongoose .insertMany 不是函数

Posted

技术标签:

【中文标题】nestjs mongoose .insertMany 不是函数【英文标题】:nestjs mongoose .insertMany is not a function 【发布时间】:2021-12-10 06:44:50 【问题描述】:

我一直坚持使用“insertMany”。谁能解释如何使用这种方法? Nest 官方文档对这种认识只字未提。 https://docs.nestjs.com/techniques/mongodb

上传.model.ts

import  Schema, Document  from 'mongoose';

export const Upload = new Schema(
  name:  type: String, required: true ,
  usernameCreate:  type: String, required: true ,
  dateCreate:  type: Date ,
);

export interface IUpload extends Document 

  readonly _id: Schema.Types.ObjectId;
  readonly name: string;
  readonly dateCreate: Date;
  readonly usernameCreate: string;

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,
      ;
    );
    const createUploads = new this.uploadModel();
    return createUploads.insertMany(arr);
  

终端

TypeError: createUploads.insertMany is not a function

"@nestjs/mongoose": "^7.2.0",
"mongoose": "^5.11.9",

【问题讨论】:

【参考方案1】:

我意识到 Document 没有这个方法。相反,我需要从 Model

调用它
async create( files, body ): Promise<any> 
    const arr = files.map((file) => 
      return 
        name: file.filename,
        dateCreate: body.dateCreate,
        usernameCreate: body.usernameCreate,
      ;
    );
    return this.uploadModel.insertMany(arr);
  

【讨论】:

以上是关于nestjs mongoose .insertMany 不是函数的主要内容,如果未能解决你的问题,请参考以下文章

@nestjs/mongoose 的文档

NestJS 和 Mongoose 使用 Mongoose-Sequence

NestJs/Mongoose 中的自动增量序列

如何用 jest 在服务 (NestJS) 中测试模型 (Mongoose)

NestJS/Mongoose:序列化不排除普通输出中的属性

如何在 NestJs 和 typescript 中使用 `mongoose-delete` 插件?