Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies.

Firstly, I have a function that adds data to Firebase:

  addpost() {
    let newposts = new Posts(
      this.addForm.value
    )   
    this.postsservice.addPosts(newposts);
  } 

Next: service.ts

  addPosts(posts: Posts){
        console.log(posts)
        this.postsCollection.add(posts);
    }

Model.ts

export class Posts {
    id?: string;
    title?: string;
    description?: string;
    upload?: string;

    constructor(obj: any) {
        this.title = obj && obj.title
        this.description = obj && obj.description,
        this.upload = obj && obj.upload
    }
    }

My Cloud Firestore

After adding data, I encounter the following error:

core.js:4352 ERROR FirebaseError: Function DocumentReference.set() called with invalid data. Data must be an object, but it was: a custom object (found in document posts/OLYLatFTZFr0zVuM3Q4S) at new n (http://localhost:4200/vendor.js:151375:23) at Fs (http://localhost:4200/vendor.js:165124:16) at t.s_ (http://localhost:4200/vendor.js:164842:16) at Us (http://localhost:4200/vendor.js:165077:37) at ks (http://localhost:4200/vendor.js:164882:5) at n.set (http://localhost:4200/vendor.js:166427:40) at n.add (http://localhost:4200/vendor.js:166941:59) at AngularFirestoreCollection.add (http://localhost:4200/vendor.js:33999:25) at PostsService.addPosts (http://localhost:4200/main.js:498:30) at PostsComponent.addpost (http://localhost:4200/main.js:1014:27) defaultErrorLogger @ core.js:4352 handleError @ core.js:4400 handleError @ core.js:8765 executeListenerWithErrorHandling @ core.js:15217 wrapListenerIn_markDirtyAndPreventDefault @ core.js:15249 schedulerFn @ core.js:24872 __tryOrUnsub @ Subscriber.js:183 next @ Subscriber.js:122 _next @ Subscriber.js:72 next @ Subscriber.js:49 next @ Subject.js:39 emit @ core.js:24841 onSubmit @ forms.js:5552 FormGroupDirective_submit_HostBindingHandler @ forms.js:5605 executeListenerWithErrorHandling @ core.js:15214 wrapListenerIn_markDirtyAndPreventDefault @ core.js:15249 (anonymous) @ platform-browser.js:582 invokeTask @ zone-evergreen.js:399 onInvokeTask @ core.js:27474 invokeTask @ zone-evergreen.js:398 runTask @ zone-evergreen.js:167 invokeTask @ zone-evergreen.js:480 invokeTask @ zone-evergreen.js:1621 globalZoneAwareCallback @ zone-evergreen.js:1647

Answer №1

According to the error message, Firestore does not allow custom objects to be used. It is recommended to provide a plain JavaScript object instead. In the end, you should aim to create something similar to the following:

this.postsCollection.add({
  title: "tttt",
  description: "ddddd",
  upload: "uuuu"
});

Consider using an interface to define this object, rather than creating a class that needs to be instantiated with new.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating unique navigation bar elements

I'm currently working on an application and facing an issue with the navigation from the Component to NavbarComponent. If you'd like to check out the application, you can visit: https://stackblitz.com/github/tsingh38/lastrada The goal is to hav ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

Incorrect Column Header Display in React with Kendo-UI Grid

I have a React application using redux as state manager. In this application we are deciding to use Kendo Ui grids. The first test is Ok but we noticed that the columns are totally wrong. We define only 5 Columns to be displayed in the table but we noticed ...

Mastering Angular 2 Reactive Forms: Efficiently Binding Entire Objects in a Single Stroke

Exploring reactive forms in Angular 2 has led me to ponder the possibility of binding all object properties simultaneously. Most tutorials show the following approach: this.form = this.fb.group({ name: ['', Validators.required], event: t ...

Creating an Angular feature module with the aim of converting it into an Angular library

Currently, I am developing an angular feature module as a library to enable us to create individual modules without the need to rebuild the entire angular application. While this approach seems to be functioning well, my question is whether it is conside ...

Troubleshooting dynamic route issues in Angular 6 when making changes in *ngFor

`<div *ngFor="let data of projects"> <a [routerLink]="'/projects/'+data.project_id"> {{data.project_name}}</a> </div>` When I click on the link, the URL changes from http://localhost:4200/projects/1 to http://localhost ...

Tips for managing numerous nested subscriptions

Looking to extract the id parameter from the route, fetch the corresponding task, and then its parent if applicable. Angular CLI: 7.1.4 Node: 11.6.0 OS: linux x64 Angular: 7.1.4 @angular-devkit/architect 0.11.4 @angula ...

Comprehensive compilation of Typescript error codes along with solutions

Where can I find a comprehensive list of Typescript error codes and their corresponding fixes? I frequently encounter errors during compilation, such as: data_loader_service.ts(10,13): error TS1005: '=>' expected. data_loader_service.ts(10,24 ...

Guide to setting data types for [key, value] pairs within a forEach iteration

I am currently encountering a typescript syntax error in my project that is indicating the need to define the prodStatus variable... const products = { 1: {isUpdating: false, qty: 2}, 2: {isUpdating: true, qty: 4} } const updatingProducts: Array< ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

Using React.lazy, Suspense, and react-router-dom for code splitting in React does not function as intended

I'm currently working on setting up a simple example that is similar to the concept of lazy-loading route components as explained here: https://reactjs.org/docs/code-splitting.html#route-based-code-splitting The idea is to dynamically load ModuleOne ...

Angular with NX has encountered a project extension that has an invalid name

I am currently using Angular in conjunction with nx. Whenever I attempt to execute the command nx serve todos, I encounter the following error: Project extension with invalid name found The project I am working on is named: todos. To create the todos app ...

Transforming TypeScript snapshot data in Firebase Cloud Functions into a string format for notification purposes

I've encountered the following code for cloud functions, which is intended to send a notification to the user upon the creation of a new follower. However, I'm facing an issue regarding converting the snap into a string in order to address the er ...

The Angular material table is having compilation issues due to an unexpected closing tag for "ng-container"

Currently, I am in the process of working on an Angular project that involves integrating Angular Material version 5.2.5. Below is a snippet from my app.component.ts: import { Component } from '@angular/core'; import {MatTableDataSource} from & ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Transforming every piece of TypeScript code into JavaScript on the server-side

I'm relatively new to developing Node.js applications for production. I've created an app using TypeScript for the backend of my Node.js project. Currently, in the package.json file, I have the following script section: "scripts": { ...

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...