l2aelba
l2aelba

Reputation: 22167

Firebase Firestore: How to get ref from snapshot via using async/await

I am using Cloud Firestore in Firebase functions with Node.js 8

Simple open question is: Does it possible to get ref from .get() via using async/await?

Example:

const snapshot = await db.collection(/*..*/).doc(/*..*/).get();
const data = snapshot.data();
const ref = /* ???? */
// Then using...
ref.update({/*..*/});

or should I just do like?

const ref = db.collection(/*..*/).doc(/*..*/);
const snapshot = await ref.get();
/* so on.../*

Upvotes: 1

Views: 2558

Answers (1)

we22gz
we22gz

Reputation: 403

If you are trying to get a new reference from your snapshot constant then its possible I would so it this way example

const areaSnapshot = await admin.firestore().doc("areas/greater-boston").get()
const bostonCities = areaSnapshot.data().cities;
const allAreas = await areaSnapshot.ref.parent.doc("new-york").get()
const nyCities= allAreas.data().cities
console.log(bostonCities, nyCities)

update document

    //to update document
    const areaSnapshot = await admin.firestore().doc("areas/greater-boston").get()
    const allAreas = areaSnapshot.ref.parent.doc("new-york").update({
                    capital: {
                        liberty: true
                    }
                })
     await allAreas
                .then(() => {
                    console.log("success")
                })
                .catch(err => console.log(err))

Source: https://firebase.google.com/docs/firestore/manage-data/add-data

Upvotes: 2

Related Questions