estn
estn

Reputation: 1203

Firestore default users data initialization

I am creating a game and I want to store completed game levels on firestore for each user.

Now my problem is that I will have to initalize this data once - I want to add a document for new user and a pojo that containts map of level ids and boolean for completed/uncompleted.

So I need to execute some kind of logic like "if document with this id doesnt exist, then add that document and add default data that means user hasnt completed any levels". Is there some way that would guarantee Id have to execute this logic only once? I want to avoid some kind of repeating/re-try if something fails and so on, thanks for your suggestion

Upvotes: 0

Views: 1635

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599101

The typical approach to create-a-document-if-it-doesn't-exist-yet is to use a transaction. Based on the sample code in the documentation on transactions:

// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(sfDocRef).then(function(sfDoc) {
        if (!sfDoc.exists) {
            transaction.set(sfDocRef, { count: 1 });
        }
    });
}).then(function() {
    console.log("Transaction successfully committed!");
}).catch(function(error) {
    console.log("Transaction failed: ", error);
});

Also see:

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317497

That's what a transaction is for (definitely read the linked docs). In your transaction, you can read the document to find out if it exists, then write the document if it does not.

Alternatively, you may be able to get away with a set() with merge. A merged set operation will create the document if it doesn't exist, then update the document with the data you specify.

Upvotes: 2

Related Questions