Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Last active April 3, 2022 16:15
Show Gist options
  • Save gregfenton/251f19d236bd8feb155ea7c5a642b4c6 to your computer and use it in GitHub Desktop.
Save gregfenton/251f19d236bd8feb155ea7c5a642b4c6 to your computer and use it in GitHub Desktop.
A super simple command-line Node script to add a document to Firestore
/**
* firestore_add_doc.js
*
* This script is assumed to live in an existing Javascript project that has its own package.json.
* I store this script in <PROJECT_ROOT>/tools/misc/.
*
* To use:
* 1. npm init -y
* 2. npm install firebase esm
* 3. Edit this code to set for USER1 and FIREBASE_CONFIG
* 4. node -r esm firestore_add_doc.js
*
* NOTE: this code works with the Firebase Web SDK "v9 modular API".
*
*/
import {initializeApp} from 'firebase/app';
import {getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import {
Bytes,
doc,
getFirestore,
setDoc
} from 'firebase/firestore';
let APP, AUTH, FIRESTORE;
// Firebase Console >> Authentication
const USER1 = {
email: '[email protected]', // USER THAT EXISTS IN FIREBASE AUTH
password: 'let_me_in',
};
// Firebase Console >> Project Overview >> General >> Apps
// (use existing app values or click Add app to create new WEB app)
const FIREBASE_CONFIG = {
apiKey: xxx,
appId: xxx,
authDomain: xxx,
databaseURL: xxx,
messagingSenderId: xxx,
projectId: xxx
};
const initializeFB = async () => {
console.log(` Initialize Firebase`);
APP = initializeApp(FIREBASE_CONFIG);
AUTH = getAuth(APP);
FIRESTORE = getFirestore(APP);
try {
await signInWithEmailAndPassword(AUTH, USER1.email, USER1.password);
let currUser = AUTH.currentUser;
console.log(` Logged in with USER1 -- UID is (${currUser.uid})`);
} catch (ex) {
console.error(ex.message);
throw ex;
}
};
const main = async () => {
console.log('>>> START - ', Date());
try {
await initializeFB();
let theData = {
strVal: "hello",
numVal: 1234,
bytesVal: Bytes.fromUint8Array(new Uint8Array([21,31]))
};
const docRef = doc(FIRESTORE, "test/test123");
await setDoc(docRef, theData);
console.log(` Successfully wrote to: ${docRef.path}`);
console.log(' Now check the Firebase Console to see this lovely doc!');
} catch(ex) {
console.error("UH-OH! ", ex.message);
throw ex;
}
console.log('>>> DONE - ', Date());
process.exit();
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment