Home > Mobile >  firestore: user Array.includes with a DocumentReference
firestore: user Array.includes with a DocumentReference

Time:08-29

I'm trying check if an array with DocumetReferences contains a specific ref.

That's my attempt:

const likedWorkouts = user.collection('additional').doc('liked');
const snapshot = await likedWorkouts.get();
const exists = snapshot.exists;
hasLiked = snapshot.data()?.liked?.includes(workout); // This part (workout is a DocumentReference)

CodePudding user response:

A DocumentReference is an object and you cannot compare them directly. You can use the isEqual() method to compare the refs:

hasLiked = !!snapshot.data()?.liked?.find((likeRef) => likeRef.isEqual(workout));

// Alternatively, you can compare the paths
// likeRef.path === workout.path

The DocumentReference in the new Modular SDK doesn't not have isEqual() method but instead there is a top level function refEqual(). It can be used as follows:

import { refEqual } from "firebase/firestore";

hasLiked = !!snapshot.data()?.liked?.find((likeRef) => refEqual(likeRef, workout));

Checkout MDN for more information on objects.

  • Related