用猫鼬保存对象数组

时间:2020-10-15 15:36:54

标签: mongodb mongoose nestjs

我想保存一个与此类似的结构

"Countries": [
{
"Country": "Afghanistan",
"CountryCode": "AF",
"Slug": "afghanistan",
"NewConfirmed": 66,
"TotalConfirmed": 39994,
"NewDeaths": 1,
"TotalDeaths": 1481,
"NewRecovered": 46,
"TotalRecovered": 33354,
"Date": "2020-10-15T12:50:05Z",
"Premium": {}
},
{
"Country": "Albania",
"CountryCode": "AL",
"Slug": "albania",
"NewConfirmed": 203,
"TotalConfirmed": 15955,
"NewDeaths": 5,
"TotalDeaths": 434,
"NewRecovered": 87,
"TotalRecovered": 9762,
"Date": "2020-10-15T12:50:05Z",
"Premium": {}
},

然后我使用NestJS创建了一个带有类和子类的架构:

import { Prop, Schema, SchemaFactory, } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type CountrySummaryDocument = CountrySummary & Document;

class SubCountrySchema {
  @Prop()
  Country: string;
  @Prop()
  CountryCode: string;
  @Prop()
  Slug: string;
  @Prop()
  NewConfirmed: number;
  @Prop()
  TotalConfirmed: number;
  @Prop()
  NewDeaths: number;
  @Prop()
  TotalDeaths: number;
  @Prop()
  NewRecovered: number;
  @Prop()
  TotalRecovered: number;
  @Prop()
  Date: Date;
}
@Schema()
class CountrySummary extends Document {
  @Prop({ type: SubCountrySchema })
  name: SubCountrySchema
}


export const CountrySummarySchema = SchemaFactory.createForClass(CountrySummary);

有人对我如何将整个阵列保存到一个新的单个集合中有任何想法吗?

我尝试过这种方法,但是当然arr是不可迭代的

 async createCountrySummary() {
        const result = await this.getCountrySummaryData()
        //console.log('1', result.data.Countries)
        const newArr = []
        const arr = result.data.countries;
        for (const item of arr) {
            newArr.push(item)
        }
        const newCountrySummart = new this.countrysummaryModel({
            newArr
        })
        const newCountryValue = await newCountrySummart.save();
        return newCountryValue.id as string;




    }

在此之前,我尝试映射整个对象,但也无法获取值。

async createCountrySummary() {
        const result = await this.getCountrySummaryData()
        //console.log('1', result.data.Countries)
        const newCountrySummary = new this.countrysummaryModel({
        });

        result.data.Countries.map(c => {
            console.log(newCountrySummary)
            newCountrySummary.name.Country = c.Country,
                console.log('1', newCountrySummary.name.Country)
            console.log('2', c.Country)
            newCountrySummary.name.CountryCode = c.CountryCode,
                newCountrySummary.name.Slug = c.slug,
                newCountrySummary.name.NewConfirmed = c.NewConfirmed,
                newCountrySummary.name.TotalConfirmed = c.TotalConfirmed,
                newCountrySummary.name.NewDeaths = c.NewDeaths,
                newCountrySummary.name.TotalDeaths = c.TotalDeaths,
                newCountrySummary.name.NewRecovered = c.NewRecovered,
                newCountrySummary.name.TotalRecovered = c.TotalRecovered
            newCountrySummary.name.Date = new Date();


        })
        const newResult = await newCountrySummary.save()
        return newResult.id as string;
    }

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以在Nestjs中使用Mongoose在架构中使用数组。

首先声明Schema,然后在对象内部操作数组并创建它。

我在下面举例说明插入的样子。

// SubCategory.ts
import { Document, Types } from 'mongoose';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
import { OnlyNotDeleted } from '@utils/MongooseUtils';
import { Category } from './Category';
import { User } from './User';

@Schema()
export class SubCategory extends Document {
    @ApiProperty()
    @Prop()
    name: string;

    @ApiProperty({
        type: () => User,
    })
    @Prop({
        type: Types.ObjectId,
        ref: `${User.name}`,
    })
    createdBy: string | User;

    @ApiProperty({
        type: () => [Category],
    })
    @Prop({
        required: false,
        default: [],
        type: [Types.ObjectId],
        ref: 'Category',
    })
    categories?: string[] | Category;

    @ApiProperty()
    @Prop({
        required: false,
        default: () => Date.now(),
    })
    createdAt?: Date;

    @Prop({
        type: Boolean,
        default: false,
        select: false,
    })
    isDeleted?: boolean;
}

export const SubCategorySchema = SchemaFactory.createForClass(SubCategory);

SubCategorySchema.pre('find', async function (next) {
    OnlyNotDeleted(this);
    next();
});

SubCategorySchema.pre('findOne', async function (next) {
    OnlyNotDeleted(this);
    next();
});

插入示例中使用的DTO文件

// store-subCategory.dto.ts
import { validateOrReject, IsString, Validate, IsOptional, IsArray } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { IsObjectId } from '@/shared/validations/IsObjectId';

export class StoreSubCategoryDTO {
    @ApiProperty()
    @IsString()
    name: string;

    createdBy: string;

    @ApiProperty()
    @IsArray()
    @Validate(IsObjectId, {
        each: true,
    })
    @IsOptional()
    categories?: string[];

    async validate(): Promise<void> {
        await validateOrReject(this);
    }
}

在subCategories.service.ts中插入保险开关

// Insert cutout inside subCategories.service.ts
async store(storeDTO: StoreSubCategoryDTO, firebaseUser: FirebaseUser): Promise<SubCategory> {
        const user = await this.usersService.getOneByFirebaseId(firebaseUser.uid);
        storeDTO.createdBy = String(user._id);
        this.logger.log(`Usuário ${user.name} cadastrando ${SubCategory.name} ${storeDTO.name}`);

        return await this.subCategoryModel.create(storeDTO);
    }

插入的最简单示例

async store(): Promise<SubCategory> {
        const storeDTO = new StoreSubCategoryDTO();
        storeDTO.name = 'Name';
        storeDTO.createdBy = 'User name';

        storeDTO.categories = ['categoryId1', 'categoryId2'];
        return await this.subCategoryModel.create(storeDTO);
    }