首页 > 解决方案 > nestjs mongoose .insertMany 不是函数

问题描述

我坚持使用“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;
}

上传.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",

标签: node.jsmongoosenestjs

解决方案


我意识到什么Document没有这个方法。相反,我需要从模型中调用它

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

推荐阅读