manu
manu

Reputation: 21

How to store firestore collection reference and add as field for different collection in firebase?

like shown in pic the id is from blogs collection document idwith rich text editor I am setting my blogDetails collection so my question is that when I post bloDetails I want two field one is blog which I am getting fine and second is blogID field which will be like (blogID:/blogs/blogs collection id) this blog collection id will come from blogs collection id

I have collection of blogs and also a collection of blogDetails. I want to set blogs collection, document Id as reference data type field in blogDetails collection document's field and I want to do it when I add blogDetails to firestore,

here is the code for adding blogDetails, I want to add blogID something like this,

(blogID:/blogs/(blogs_document-id)

Please help. Thank you.

    export const setBlogDetails = (blog) => {
        return (dispatch) => {
            firestore.collection("blogDetails").add({
                ...{ blog },}).then(() => {
                    dispatch({
                        type: ADD_BLOG_DETAILS,
                        blog
                     });
                }).catch((err) => {
                  console.log(err);
            });
        };
    }

Here is code for setting blogs collection:

    export const setBlog = (blogData) => {
        return (dispatch) => 
        {
            firestore.collection("blogs").add({
                ...blogData,
                }).then(() => {
                dispatch({
                    type: ADD_BLOG,
                });
            }).catch((err) => {
                console.log(err);
            });
        }
    }

Upvotes: 1

Views: 135

Answers (1)

Vo Quoc Thang
Vo Quoc Thang

Reputation: 1396

You can combine two operations like this: (I assume you want to store an Id of blog details in the Blogs Table)

setBlogDetails = (blog) => { 
        return (dispatch) => { 
            firestore.collection("blogs")
                 .add({ ...{ blog },})
                 .then((docRef) => { 
                       // docRef reference to the newly created blog.
                       dispatch({ type: ADD_BLOG_DETAILS, blog });
                       return firestore.collection("blogsDetails").add({...blog, blogRef: docRef.id});
                   })
                 .then(() => {
                      dispatch({
                      type: ADD_BLOG,
                  });
                 .catch((err) => { console.log(err); }); }; 
        }

Upvotes: 1

Related Questions