How to enable `ignoreUndefinedProperties` in node js - javascript

I am developing a REST api for my application in Nodejs and Express. But each time i try to send a request I get an undefined error. Please how can i enable 'ignoreundefinedproperties'

once you import the firebase-admin sdk (in Typescript) like this
import * as firestore from "firebase-admin";
then you just need to set the setting like this :
const db = firestore.firestore();
db.settings({ ignoreUndefinedProperties: true })

If you are getting errors for calling this more than once, I recommend putting admin.firestore().settings({ignoreUndefinedProperties:true}); in the same place you have admin.initializeApp();
Here's how I did it in my Typescript project
initialize.ts:
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
admin.firestore().settings({ignoreUndefinedProperties:true});
Top of index.ts:
import './initialize.ts'

For anyone using the v9 API:
import { getFirestore, connectFirestoreEmulator, initializeFirestore } from 'firebase/firestore'; // Firebase v9+
// Must be called before getFirestore()
initializeFirestore(app, {
ignoreUndefinedProperties: true
});
const firestore = getFirestore(app);

If you're facing error (Firestore has already been initialized. You can only call settings() once) even after trying other answers, restart your IDE/VSCode and terminal. This is what worked for me.

Related

Firebase currentUser and onAuthStateChanged

I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.
I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.
I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)
My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "#react-native-async-storage/async-storage";
import { firebaseConfig } from "./firebase/firebaseConfig";
firebase.initializeApp(firebaseConfig);
firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
console.log("onAuthStateChanged called: ", user);
if (user) {
await AsyncStorage.setItem('#isLoggedIn', '1');
} else {
await AsyncStorage.setItem('#isLoggedIn', '0');
}
});
export default firebase;
But I get an error:
undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
to Login I use:
userCredential = firebase
.auth()
.signInWithEmailAndPassword(data.email, this.state.password);
I had this exact same issue. I solved it by adding "firebase": "^8.9.1" to package.json, running yarn install and changing the import import firebase from "firebase" (remove all the other imports you have). Apparently selective imports have a bug in v8, but at least it works well :)

service firestore is not available

I'm trying to connect to my firestore using plain javascript. (I wanna get up to speed and running for now)
index.js:
import app from './firebase.js'
import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js'
const db = getFirestore(app)
However, this throws an error: Uncaught Error: Service firestore is not available
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = {
// configs
};
// Initialize Firebase
let app
export default app = initializeApp(firebaseConfig);
Then I import the script in my index.html:
<!DOCTYPE html>
....
<script type="module" src="index.html"></script>
Note: I can read and write to the firestore using firebase web interface.
So if you want to use plain js (without bundlers like webpack), you would need to put your JS code into script tag like so:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = { ... };
const app = initializeApp(firebaseConfig);
</script>
Otherwise, if you want to use it like you intended to do so, you would need to:
install a firebase package
a module bundler (e.g. webpack) to bundle the files for you
Using npm, but got the same error message.
Restarted terminal & uninstalled and reinstall firebase, then worked...not sure which one that did it though.
You need to upgrade your firestore version 9.0.0 to 9.4.0 and it work fine
import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js";
Change your import link import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
to import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
just update the firebase version from 9.0.0 to 9.0.1

firebase.apps.length of undefined

Environment
Operating System version: Windows 11
Browser version: Chrome
Firebase SDK version: 9.0.2
Firebase Product: database
firebase.apps.length of undefined
Issue:
I dont know what happened today morning it opened my code and it shows something like
app.firestore() is not a function and shows firebase.apps.length of undefined
Code:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app()
const db = app.firestore()
The syntax for Firebase has changed in v9, as everything is now modular/functional. You can now safely get an app with:
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
I highly recommend keeping Firebase's own documentation and this upgrade guide handy.
Alternatively, you can keep using the older syntax by using the compatibility mode of the newer SDKs, by importing from the compat path.
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
In that case the rest of your code stays unchanged.

firebase.auth.EmailAuthProvider is undefined

This is how I import firebase into the project:
import firebase from 'firebase/app'
import firestore from 'firebase/firestore'
import auth from 'firebase/auth'
/*
Config */
const FIREBASE_CONFIG = {
...
}
/*
Get a Firestore instance */
export const firebaseInstance = firebase.initializeApp(FIREBASE_CONFIG)
Later I would just:
import { firebaseInstance } from 'database' whenever it's needed and have to access singup, login and other available API methods like for example:
firebaseInstance.auth().fetchSignInMethodsForEmail(email)
However when I am trying
firebaseInstance.auth.EmailAuthProvider as defined in the official documentation it's simply not available and returns undefined
Can somebody please suggest what can be missing?
P.S: I've tried firebaseInstance.auth().EmailAuthProvider however after researching in github thread how other people do it, I believe that is not the thing :)
Documentation says it's static method, so it doesn't make sense to call it on instance? You can find it under firebase.auth.EmailAuthProvider

Firestore arrayUnion

I'm building a basic CRUD app with vue.js and firebase. I'm trying to build out a favorites functionality and have ran into a persistent problem storing the data.
When a using clicks the add to favorites button I'm attempting to add the document id to an array in a "user profile" document. Here's the code:
export function addNewUserAction (type, key, userID){
console.log(userID);
console.log(key);
firebase.firestore().collection('userActions').add({
type: type,
listing: key,
user: userID,
time: Date.now()
})
if(type === 'favorite'){
var sendfav = db.collection('userProfiles').doc(userID).update({
favs: firebase.firestore.FieldValue.arrayUnion(key)
});
}else if(type === 'xout'){
var sendxout = db.collection('userProfiles').doc(userID).update({
xouts: firebase.firestore.FieldValue.arrayUnion(key)
});
}else{
console.error(type + " is not a user action");
}
}
I get the following error in the console:
Uncaught TypeError: Cannot read property 'arrayUnion' of undefined
at addNewUserAction
I have firebase and the db ref imported, and have ran a bogus .set() through each reference to confirm they are pointing at the right spots. I also already have the arrays created in 'userProfile' document.
The firebase install is fresh, like last week fresh, so I should have the function in my build.
Seems that arrayUnion is just not working. Any ideas? The other firestore functions are workin so I'm not sure. Am I blatenly missing something? Thanks
If you are using the Admin SDK
I was having some random errors similar to this, among others as I was experimenting. It turns out it was because I was using firebase admin sdk which requires a slight change compared to the web SDK documentation. If you are using firebase admin, replace
firebase.firestore.FieldValue.arrayUnion(...
with
admin.firestore.FieldValue.arrayUnion(...
I had the same issue...
This would not work
import { fireStore } from '../../firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: fireStore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
I changed the import and used the exact code from the Firebase Docs.
This works fine.
import * as firebase from 'firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: firebase.firestore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
Hope that helps.
Just wanted to update this. I was able to get this working by importing firebase the following way:
`import firebase from "firebase/firebase";`
I think my issue before was several problems, the first primarily was not having the correct version. I just recently updated to 5.8.4 which completely broke my app. I tried the above as a possible solution and it got my app working again. That led me to try it on with arrayUnion and it worked. Hopefully thats helpful to someone. Thanks all for the help.
Update 10/11/19
So I wanted to add another update to this in case someone new to firebase is chasing their tail with this as I have been.
So the solution I included above works because it uses the entire firebase SDK package ('firebase/firebase') which is fine, however you will importing the entire firebase package which is not ideal. You constantly see an alert in your console that you're using the development SDK
If you're trying to optimize your app and only import the firebase packages you need ( i.e. auth, datatbase, etc.) you need to import the firebase app object from 'firebase/app' then import the required packages. The key is to import as an object as the firebase docs call for:
import * as firebase from 'firebase/app';
Import 'firebase/auth'
If you use:
import firebase from 'firebase/app' this will not work.
Hope that helps someone. I know it's probie stuff but it stumped me for a while in my learning curve.
Firestore - Pass Array To arrayUnion()
let myArray = ["1", "2", "3"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion.apply(this, myArray)
});
This worked for me^
For Vue.js Developers
I have created a folder named firebase in src folder, then i have created a file named init.js in firebase folder
init.js
import * as firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
// Your Firebase Config
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// utils
const db = firebase.firestore();
const auth = firebase.auth();
export { db, auth, firebase };
Now use them in whichever components you need.
Just by,
import { firebase, auth, db } from "#/firebase/init.js";
Now You can use firebase without any Errors
db.collection("users") // Collection Name
.doc(userId) // Document in Collection indexed userId
.update({
friends: firebase.firestore.FieldValue.arrayUnion(auth.currentUser.uid)
})
// friends is the array collection in firestore
Thats It

Categories