【问题标题】:Saving array of objects with mongoose用猫鼬保存对象数组
【发布时间】:2021-01-30 03:27:35
【问题描述】:

我想保存一个类似这样的结构

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

谁能帮帮我?

【问题讨论】:

    标签: mongodb mongoose nestjs


    【解决方案1】:

    您可以在 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);
        }
    

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2017-06-09
      • 2019-07-14
      • 1970-01-01
      • 2020-07-27
      相关资源
      最近更新 更多