Filtering firebase query on array of ids in any order to return same result

Viewed 214

I am working with firebase for real-time communication in an app. Currently, I need to be able to have an upsert function that returns a "room" based on the people ids passed, regardless of order.

For example ['1','2'] and ['2', '1'] should return the same room on upsert.

Here's the current code to get a room based on ids passed in args.

if (Array.isArray(args.peopleIds)) {
    const existingRoom = await admin
      .firestore()
      .collection('rooms')
      .where('peopleIds', '==', args.peopleIds)
      .get()

    if (!existingRoom.empty) {
      const doc = existingRoom.docs[0]
      return { id: doc.id, ...doc.data() }
    }
  }

Currently, if one of my rooms in Firebase has peopleIds of ['1', '2'], when I call the upsert with the ids in reverse order, it will create a new room.

After reading the Firebase docs on querying, I don't see a great way to accomplish this other than MAYBE sorting the ids prior to upsert so they are continuously in the same order.

I'm curious if anyone has found a better solution.

0 Answers
Related