flamelink / flamelink-js-sdk

🦊 Official Flamelink JavaScript SDK for both the Firebase Realtime database and Cloud Firestore
https://flamelink.github.io/flamelink-js-sdk
MIT License
43 stars 5 forks source link

Add content as relational data #155

Closed Twansparant closed 3 years ago

Twansparant commented 3 years ago

Hi there,

I can't seem to find this in any documentation; How do you set field data as document reference?

I have a schema with a Select Relational field. When I select a document in the select field in the CMS itself, I can see it's saved as a reference field in Cloud Firestore with as document path: fl_content/id.

But how can I achieve the same using the JS SDK?

flamelinkApp
    .content
    .add({
        schemaKey: 'mySchema',
        entryId: myId,
        data: {
            relationalField: id // <- in what format?
        }
    })

I tried setting the relationalField as string with just the document id, with fl_content/${id} and with a full document object, but none of them seem to work?

How are you supposed to set the field value as document reference? Thanks!

cspecter commented 3 years ago

HI @Twansparant . This took me forever to figure out, but if you are using Cloud Firestore you need to fetch a Firebase DocumentReference for any interaction with a relational field. For creating , fetching data or updating entries. If would need to look something like this:

// If you are relating to another entry in fl_content you will need to 
// do something like this. If it's a file relation Flamelink give you a way 
// to get the reference. All you need in either case is the "entryID".

// For a "fileId" use flamelink.storage.fileRef()

import {firebaseClient} from '.client.js'

const add = async (schemaKey, relationalId) => {
    const documentReference = await firebaseClient
            .firestore()
            .collection('fl_content')
            .doc(relationalId)

    flamelinkApp
        .content
        .add({
            schemaKey,
            data: {
                relationalField: documentReference // <- This is now a Firebase DocumentReference
            }
        })
}

Hope this helps. You need to do the same thing if you want to filter by a relational field. You need to convert the ID to a DocumentReference.

Twansparant commented 3 years ago

Yes, I figured that out too! Thanks though!