How to add a record to a firebase collection using an ionic app?

Viewed 352

I am trying to create a record in firebase using my ionic app.

I have already successfully connected to the firebase app because I am using auth() to log in users already.

But now, I am not able to create records when I try to add to a collection. Below is my latest code:

post(): void {
    console.log('attempting post')
    firebase.firestore().collection('posts').add({
      text: this.text,
      created: firebase.firestore.FieldValue.serverTimestamp(),
      owner: firebase.auth().currentUser.uid,
      owner_name: firebase.auth().currentUser.displayName
    }).then((doc) => {
      console.log(doc);
    }).catch((err) => {
      console.log(err)
    })
  }

“attempting post” is logged to the console, so I’m getting into the post() method, but nothing else is appearing in the console, not even an error message.

I have removed the database rules, so anybody can write to the firestore now. Here is what I have in environment.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: "AIzaSyCD9qZV905SELHWvEYoaNqoKKISAO4ddS8",
    authDomain: "feedlyapp-70714.firebaseapp.com",
    databaseURL: "https://feedlyapp-70714.firebaseio.com",
    projectId: "feedlyapp-70714",
    storageBucket: "feedlyapp-70714.appspot.com",
    messagingSenderId: "1031920662829",
    appId: "1:1031920662829:web:7d5947dd1aed5010c03ba4",
    measurementId: "G-RSDBEJQBLS"
  }
};

Feel free to try & write to this DB, because I am having no luck with it so far.

Can someone please tell me what I’m doing wrong, & how it can be resolved?

Also, I've tried to create a collection from the firebase console itself, & it's not allowing me to add records.

1 Answers

There are many documentation and articles that might help you with examples of creating documents with Firebase, using Ionic.

As per the article Building a Ionic Firebase App step by step, this below code sample tries to add posts to a collection, within a collection of people.

createPost(value){
   return new Promise<any>((resolve, reject) => {
     let currentUser = firebase.auth().currentUser;
     this.afs.collection('people').doc(currentUser.uid).collection('posts').add({
       title: value.title,
       description: value.description,
       image: value.image
     })
     .then(
       res => resolve(res),
       err => reject(err)
     )
   })
 }

This code is not tested, but I hope it helps you as a starting point.

Besides that, the below articles should provide you with more information and examples of how to achieve the creation of an application with Firebase and Ionic.

Let me know if the information helped you!

Related