【发布时间】: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;
}
谁能帮帮我?
【问题讨论】: