3

Imagine any structure:

collection/document

In every document there is a value, like some kind of score. Then I order my collection by this score: collection("collection").orderBy("score").

I can retrieve a specific document out of this collection("collection").orderBy("score").where(FieldPath.documentId(), "==", "document1234")

Now I wonder whether or not it is possible to get the position of my specific document in order.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

1 Answers1

2

You can add a function trigger to your document which assigns the index. You position is then just the index field. You would need to add a trigger for onUpdate, onDelete aswell.

exports.updateScorePosition = functions.firestore.document('collection/{documentId}').onWrite(event => {
    return db.collection('collection').orderBy('points').get()
        .then(snapshot => {
            let updatePointsBatch = db.batch();
            let i = 0;
            snapshot.docs.forEach(doc => {
                updatePointsBatch.update(doc.ref, { index: i})
                i++;
            });
            return updatePointsBatch.commit();
        })
        .catch(error => console.log('error: ' + error));
});

You could likely optimize this by only updating indexes after the current document index if you are working with a large collection

Linxy
  • 2,525
  • 3
  • 22
  • 37
  • This is an option, but I surely do not want to waste a Function invocation for that. I would have an opportunity to do something like this in another Function, but I am not sure if it is a good idea to go through all documents on every invocation because my collection is very big, i.e. the size has an open end, which would make this super slow eventually. – creativecreatorormaybenot Mar 22 '18 at 10:52