함수 DocumentReference.set()이 잘못된 데이터로 호출되었습니다.지원되지 않는 필드 값: 사용자 지정 예산 개체
아래 코드는 오늘까지 정상적으로 작동합니다.하지만 지금은 작동하지 않고 아래 오류가 발생하는지 모르겠습니다.이유를 말씀해 주시겠습니까?
오류: 잘못된 데이터로 호출된 함수 DocumentReference.set()입니다.지원되지 않는 필드 값: 사용자 지정 예산 개체
export class Project {
id: string = null;
name: string;
budgetList?: Budget[];
}
export class Budget {
id: string;
amount: number;
contingency: number = 20;
budgetGroup: BudgetGroup = new BudgetGroup();
creationTime: string;
}
코드:
async create(data: DtoProject): Promise<Project> {
try {
const projectId: string = this.fireStore.createId();
const budgets = this.budgetProvider.createBudgets(data.budgetList, projectId);//budgets
const proj: Project = {
id: data.id,
name: data.name,
budgetList: budgets,//here it has the error
}
proj.id = projectId;
await this.fireStore.doc<Project>(`projects/${projectId}/`).set(proj));//project
}
}
createBudgets(data: Budget[], projectId: string): Budget[] {
let budgets: Budget[] = [];
forEach(data, (d) => {
const budgetId: string = this.fireStore.createId();
d.id = budgetId;
budgets.push(d);
this.fireStore.doc<Budget>(`projects/${projectId}/budgets/${budgetId}`).set({
id: budgetId,
amount: d.amount,
contingency: d.contingency,
budgetGroup: d.budgetGroup,
creationTime: moment().format()
})
})
return budgets;
}
예산을 순수 자바스크립트 객체로 변환해야 합니다.
첫 번째 단계:
const budgets = arrayOfBudget.map((obj)=> {return Object.assign({}, obj)});
두 번째 단계:
const proj: Project = {
id: data.id,
name: data.name,
budgetList: budgets
}
그럼 가셔도 됩니다.
그런데 자바스크립트로 컴파일되는 언어로 개발할 때는 사용자 지정 객체를 사용할 수 없습니다.대신 순수 JavaScript 개체를 사용하여 Firestore 데이터베이스에 저장해야 합니다.
예를 들어 다음 클래스가 있다고 가정합니다.
export class User {
id: string;
name: string;
}
그리고 다음 코드를 실행하려고 합니다.
const user = new User();
this.db.collection('users').doc().set(user)
다음과 같은 오류가 표시됩니다.
잘못된 데이터데이터는 개체여야 하지만 사용자 지정 사용자 개체였습니다.
이제 다른 코드 라인을 실행하려고 하면:
this.db.collection('users').doc().set(Object.assign({}, user))
개체가 데이터베이스에 저장된 것을 확인할 수 있습니다.기본적으로Object.assign
다음과 같은 작업을 수행합니다.
this.db.collection('users').doc().set({id: user.id , name: user.name})
그래서 활용하세요.Object.assign
시간을 많이 절약할 수 있습니다.
갱신하다
아래 설명에서 지적했듯이 사용자 지정 개체에 대한 설명서의 내용을 여기에서 확인할 수 있습니다.보시다시피 다음과 같은 경고가 표시됩니다.
웹에서 JavaScript 개체 사용
아래에는 설명서에 나와 있는 내용의 스크린샷이 있습니다.
개체를 문자열화하고 개체로 다시 구문 분석하여 개체의 클래스 이름을 제거할 수 있습니다.
const budgets = this.budgetProvider.createBudgets(JSON.parse(JSON.stringify(data.budgetList)), projectId);
다음과 같은 스프레드 연산자를 사용할 수도 있습니다.
this.fireStore
.doc<Project>(`projects/${projectId}/`)
.set( {...proj} ))
나한테 효과가 있어요.
새 개체에 추가 방법을 사용하여 모든 값을 스프레드 연산자로 복사할 수도 있습니다.이것은 저에게 효과가 있었습니다.
const user = new User();
this.db.collection('users').add({...user});
나한테 효과가 있어요.
proj.budgetList = {...budgets}
await this.fireStore.doc<Project>(`projects/${projectId}/`).set({...proj}));
사용하는 모든 사용자에게FirestoreDataConverter
객체 유형 배열에 대해 수행한 방법은 다음과 같습니다.RecipeTag
활자의 내부에.Recipe
.
//Recipe를 추가하기 위해 호출하는 위치
const collectionRef = collection(db, collectionPath)
.withConverter(Recipe.firestoreConverter);
await addDoc(collectionRef, recipe);
//Recipe
모범을 보이다
public static firestoreConverter: FirestoreDataConverter<Recipe> = {
toFirestore: (recipe: Recipe) => {
return {
title: recipe.title,
recipeUrl: recipe.recipeUrl,
imageLink: recipe.imageLink,
tags: recipe.tags.map(tag => RecipeTag.firestoreConverter.toFirestore(tag))
};
},
fromFirestore: (snapshot: DocumentSnapshot<DocumentData>) => {
const data = snapshot.data() as Recipe
return new Recipe(data)
}
}
//RecipeTag
모범을 보이다
public static firestoreConverter: FirestoreDataConverter<RecipeTag> = {
toFirestore: (recipe: RecipeTag) => {
return {
description: recipe.description,
title: recipe.title,
};
},
fromFirestore: (snapshot: DocumentSnapshot<DocumentData>) => {
const data = snapshot.data() as RecipeTag
return new RecipeTag(data)
}
}
지도를 Firestore에 직접 추가하려고 할 때 동일한 문제에 직면했습니다(v9).
문제는 다음과 같습니다.
// Firestore module v9
// I was trying to add a Map to firestore
userInterestsMap.forEach(async (v: Map<string, number>, k: string) => {
const modelRef = doc(db, "model", k);
await setDoc(modelRef, {
'data': v // here is the issue
});
})
해결책
userInterestsMap.forEach(async (v: Map<string, number>, k: string) => {
const modelRef = doc(db, "model", k);
await setDoc(modelRef, {
'data': Object.fromEntries(v) // here is the solution
});
})
기본적으로 맵을 객체로 변환합니다.
입력한 데이터가 잘못되었음을 나타내는 오류입니다.
저는 또한 어디선가 오류가 발생했습니다. 왜냐하면 인터페이스에서 입력 필드를 제거했기 때문입니다. 입력 필드의 값을 가져와 일부 컬렉션의 문서에 업로드했기 때문입니다.
. 파일의합니다.firebase.firestore().collection("some_name").add() / set()
불필요한 필드가 있는지 없는지 확인합니다.
언급URL : https://stackoverflow.com/questions/48156234/function-documentreference-set-called-with-invalid-data-unsupported-field-val
'programing' 카테고리의 다른 글
특수 문자 VBA Excel 제거 (0) | 2023.07.10 |
---|---|
모노가 비어 있는 경우에만 작업을 수행하고 비어 있지 않은 경우에는 오류를 발생시키는 방법 (0) | 2023.07.10 |
오류에 관계없이 ts-node를 사용하는 방법은 무엇입니까? (0) | 2023.07.05 |
where 절에 대한 Oracle/PL SQL/SQL null 비교 (0) | 2023.07.05 |
mongodb 컬렉션에서 가장 오래된/최연소 게시물 찾기 (0) | 2023.07.05 |