nestjs mongoose . insertmany不是一个函数



我坚持使用&;insertmany &;谁能解释一下这个方法怎么用?Nest官方文档对这种实现只字未提。https://docs.nestjs.com/techniques/mongodb

upload.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
<<p>包/em>
"@nestjs/mongoose": "^7.2.0",
"mongoose": "^5.11.9",

我意识到文档没有这个方法。相反,我需要从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);
}

我也得到了同样的错误,我发现我正在使用新的关键字,在insertMany的时候不应该存在。

return await this.bookingSlotsRespository.create(availableSlots);

对我来说很有效。

  • availableSlots是一个我必须保存的对象数组。

你正在为模型创建一个新的实例,试试这个

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,
};
});
await this.uploadModel().insertMany(arr);
return {message:"success"}
}
}

相关内容

  • 没有找到相关文章

最新更新