Gaurav Raj
Gaurav Raj

Reputation: 246

How to add a new field in all the firebase documents?

I have a firebase application on the App Store. In the users collection in firebase, I have a bunch of fields like first_name, last_name, etc. I want to add another field (age) in all the existing documents. How can I do that? If I don't update it, the application gives errors saying that the field doesn't exist in the document.

Upvotes: 1

Views: 2256

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599341

There is nothing special about this:

  1. Read all documents.
  2. Loop over the results.
  3. Update each of them.

Since you tagged with Cloud Functions, in Node.js this would be something like:

const usersRef = db.collection('users');
const snapshot = await usersRef.get();
await Promise.all(snapshot.docs.map(doc => doc.ref.update({age: 42})));

This is based on these links from the Firebase documentation:

You might also want to look at:

Upvotes: 1

Related Questions