I am to make a blog website that can save and publish written articles within the website. I am using firebase firestore to save my data there but only problem is that when i run it, it say db is not defined at HTMLButtonElement
HTML
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js"
></script>
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js"
></script>
<script type="module" src="js/editor.js">
firebase.initializeApp({
apiKey: "AIzaSyBbHBS9rdHrbP6g7BG4_kPP9XV1vCiVewU",
authDomain: "blog-web-49668.firebaseapp.com",
projectId: "blog-web-49668",
storageBucket: "blog-web-49668.appspot.com",
messagingSenderId: "561111016179",
appId: "1:561111016179:web:eef336738659e3fbfb0d86",
});
var db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
Javascprit
publishBtn.addEventListener('click', () => {
if (articleField.value.length && blogTitleField.value.length) {
// generating id
let letters = 'abcdefghijklmnopqrstuvwxyz';
let blogTitle = blogTitleField.value.split("-").join("-");
let id = '';
for (let i = 0; i < 4; i++) {
id += letters[Math.floor(Math.random() * letters.length)];
}
// setting up docName
let docName = `${blogTitle}-${id}`;
let date = new Date(); // for published at info
//access firestore with db variable;
db.collection("blogs").doc(docName).set({
title: blogTitleField.value,
article: articleField.value,
bannerImage: bannerPath,
publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
})
.then(() => {
console.log('date entered');
})
.catch((err) => {
console.error(err);
});
}
})
You need to remove src="js/editor.js" from the script tag:
<script type="module" src="js/editor.js">
firebase.initializeApp({...
// ...
</script>
should be
<script type="module">
firebase.initializeApp({...
// ...
</script>
i have the same problem, i solve in this way
Hello, try to put this code in the "firebase.js":
let firebaseConfig = {
//your information
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export async function insert(item) {
try {
const response = await db.collection("blogs").add(item);
return response;
} catch (error) {
throw new Error(error);
}
}
export async function getItems(uid) {
try {
let items = [];
const response = await db
.collection("blogs")
.where("userid", "==", uid)
.get();
response.forEach(function (item) {
items.push(item.data());
});
return items;
} catch (error) {
throw new Error(error);
}
}
export async function update(id, completed) {
try {
let docId;
const doc = await db.collection("blogs").where("id", "==", id).get();
doc.forEach((i) => {
docId = i.id;
});
await db.collection("blogs").doc(docId).update({ completed: completed
});
} catch (error) {
throw new Error(error);
}
}
export { db };
and in the js files import:
import { insert, getItems, update, db } from "./firebase.js";
Related
i am initializing a node js app with crucial data for the app to work from a database in index.js.
index.ts
import {getInitialData} from 'initData.ts';
export let APP_DATA: AppData;
export const initializeAppData = async () => {
try {
APP_DATA = (await getInitialData()) as AppData;
if (process.env.NODE_ENV !== 'test') {
initializeMongoose();
startServer();
}
} catch (error) {
console.log(error);
}
};
initData.ts
let dbName: string = 'initialData';
if (process.env.NODE_ENV === 'test') {
dbName = 'testDb';
}
const uri = `${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`;
export async function getInitialData() {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db(dbName);
const configCursor = database
.collection('config')
.find({}, { projection: { _id: 0 } });
const config = await configCursor.toArray();
const aaoCursor = database
.collection('aao')
.find({}, { projection: { _id: 0 } });
const aao = await aaoCursor.toArray();
return { config, aao };
} catch {
(err: Error) => console.log(err);
} finally {
await client.close();
}
}
I'm using this array in another file and import it there.
missionCreateHandler
import { APP_DATA } from '../index';
export const addMissionResources = (
alarmKeyword: AlarmKeyword,
newMission: MissionDocument
) => {
const alarmKeywordObject = APP_DATA?.aao.find(
(el) => Object.keys(el)[0] === alarmKeyword
);
const resourceCommand = Object.values(alarmKeywordObject!);
resourceCommand.forEach((el) => {
Object.entries(el).forEach(([key, value]) => {
for (let ii = 1; ii <= value; ii++) {
newMission.resources?.push({
initialType: key,
status: 'unarranged',
});
}
});
});
};
I'm setting up a mongodb-memory-server in globalSetup.ts for Jest and copy the relevant data to the database from json-files.
globalSetup.ts
export = async function globalSetup() {
const instance = await MongoMemoryServer.create({
instance: { dbName: 'testDb' },
});
const uri = instance.getUri();
(global as any).__MONGOINSTANCE = instance;
process.env.MONGODB_URI = uri.slice(0, uri.lastIndexOf('/'));
process.env.JWT_SECRET = 'testSECRET';
const client = new MongoClient(
`${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`
);
try {
await client.connect();
const database = client.db('testDb');
database.createCollection('aao');
//#ts-ignore
await database.collection('aao').insertMany(aao['default']);
} catch (error) {
console.log(error);
} finally {
await client.close();
}
};
missionCreateHandler.test.ts
test('it adds the correct mission resources to the array', async () => {
const newMission = await Mission.create({
address: {
street: 'test',
houseNr: 23,
},
alarmKeyword: 'R1',
});
const expected = {
initialType: 'rtw',
status: 'unarranged',
};
addMissionResources('R1', newMission);
expect(newMission.resources[0].initialType).toEqual(expected.initialType);
expect(newMission.resources[0].status).toEqual(expected.status);
});
When runing the test, i get an 'TypeError: Cannot convert undefined or null to object at Function.values ()'. So it seems that the APP_DATA object is not set. I checked that the mongodb-memory-server is set up correctly and feed with the needed data.
When i hardcode the content of APP_DATA in index.ts, the test runs without problems.
So my questions are: How is the best practice to set up initial data in a node js app and where to store it (global object, simple variable and import it in the files where needed)? How can the test successfully run, or is my code just untestable?
Thank you!
When I try to perform google authentication with firebase, neither the googleSignInWithPopup method works, nor with any other. I am following the instructions in the documentation and nothing appears
about this error.
It does not throw any error and all functions are called
this is the code I am implementing:
const firebaseConfig = {
apiKey: "AIzaSyBTtZRgAufHwkuth3Jo-pnTTKl1tBrK92o",
authDomain: "journal-react-redux.firebaseapp.com",
projectId: "journal-react-redux",
storageBucket: "journal-react-redux.appspot.com",
messagingSenderId: "189133948252",
appId: "1:189133948252:web:99aaaedf42fdb97243ed99"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export {
db,
googleAuthProvider,
firebase
}
export const startGoogleLogin = () => {
return (dispatch) => {
firebase.auth().signInWithRedirect(googleAuthProvider)
.then(({ user }) => {
dispatch(
login(user.uid, user.displayName)
)
});
}
}
export const login = (uid, displayName) => {
return {
type: types.login,
payload: {
uid,
displayName
}
}
}
const handleGoogleLogin = () =>{
dispatch(startGoogleLogin);
}
this is all the code where it is used and declared for use.
PS: This app is made in react 17 with redux.
Could you try this code snippet? Also, make sure that Google Authentication is enabled in Firebase Console
export const loginUserWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
return auth
.signInWithPopup(provider)
.then((result) => {
return result.user;
})
}
Then you can use this code in your actions
export const logInWithGoogle = () => {
return (dispatch) => {
loginUserWithGoogle()
.then((user) => {
// ... do something with user
})
.catch(error => {
console.log(error)
})
}
}
Try to update your function to
const handleGoogleLogin = () => {
return (dispatch) => {
dispatch(startGoogleLogin);
}
}
i have i problem with this file.js ; i try to start the application but the console give me the error on the title of this post (TypeError: _firebase.default.analytics is not a function. (In '_firebase.default.analytics()', '_firebase.default.analytics' is undefined)). I'm using firebase ase database and React Native to create this app based on a common chat where differents user can join and pass messages; This is the code:
import firebase from 'firebase';
import { useCallback } from 'react';
class Fire {
constructor() {
this.init()
this.checkAuth()
}
init = () => {
if(!firebase.apps.length){
var firebaseConfig = {
apiKey: "AIzaSyCSptHIogcurTROMvzp_QB7vQ8srIbnwBk",
authDomain: "login-with-firebase-23e8e.firebaseapp.com",
projectId: "login-with-firebase-23e8e",
storageBucket: "login-with-firebase-23e8e.appspot.com",
messagingSenderId: "1099034898191",
appId: "1:1099034898191:web:b8a3a66be2d5a49d83987a",
measurementId: "G-73M58E50QL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
}
};
checkAuth = () =>{
firebase.auth().onAuthStateChanged(user => {
if(!user){
firebase.auth().signInAnonymously();
}
});
};
send = messages => {
messages.forEach(item => {
const message = {
text: item.text,
timestamp: firebase.database.ServerValue.TIMESTAMP,
user: item.user
}
this.db.push(message)
})
};
get db() {
return firebase.database().ref("messages");
};
parse = message => {
const {user, text, timestamp} = message.val()
const {key: _id} = message;
const createdAt = new Date(timestamp);
return {
_id,
createdAt,
text,
user
};
}
get = callback => {
this.db.on("child_added", snapshot => callback(this.parse(snapshot)));
};
get uid(){
return (firebase.auth().currentUser || {}).uid;
}
}
export default new Fire();
I've got a function that returns the number of records from a DynamoDB table (Things):
const table = 'Things';
const region = 'us-east-1';
const profile = 'development';
process.env.AWS_SDK_LOAD_CONFIG = true;
process.env.AWS_PROFILE = profile;
const AWS = require('aws-sdk');
AWS.config.update({ region: region });
function ddb_table_has_records(table_name) {
const ddb_client = new AWS.DynamoDB.DocumentClient();
const ddb_query_parameters = {
TableName: table_name,
Select: 'COUNT'
}
const results = ddb_client.scan(ddb_query_parameters).promise();
results.then((data) => {
console.log(data.Count);
return data;
}).catch((err) => {
console.log("Error: ", err);
})
}
console.log(ddb_table_has_records(table));
When I run this code, I get the following...
PS C:\> node .\get-count-thing.js
undefined
3951
I'm not capturing the data from the scan in the following; although, I see it in the console.log() call:
console.log(ddb_table_has_records(table));
What am I mucking up?
Posting my fix in-case anyone has the same question. I had to make two changes to retrieve the items from the table; I needed to...
...project ALL_ATTRIBUTES
...iterate over the collection of Items returned
The following was my function with changes:
function ddb_table_has_records(table_name) {
const ddb_client = new AWS.DynamoDB.DocumentClient();
const ddb_query_parameters = {
TableName: table_name,
Select: 'ALL_ATTRIBUTES'
}
const results = ddb_client.scan(ddb_query_parameters).promise();
results.then((data) => {
console.log(data.Count);
data.Items.forEach((thing) => {
console.log(thing);
});
}).catch((err) => {
console.log("Error: ", err);
})
}
I'm trying to do a query to the database, to get all documents of sub-collection "roles" to redirect to different routes.
let userRef1 = db.collection('users').doc(currentUser.uid).collection('roles')
let cont = 0
let rol = ''
let rolStatus = ''
userRef1.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
cont++
rol = doc.data().rol
rolStatus = doc.data().status
});
import { firestore } from "../../firebase";
export const loadCategories = () => {
return (dispatch, getState) => {
firestore
.collection("CATEGORIES")
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
}
})
.catch((error) => {
console.log(error);
});
};
};
I have a collection of users including uid just like yours. And for each user, it contains a sub-collection called friends.
Currently, I'm using the following code for my project without having any issues.
module.exports = ({ functions, firestore }) => {
return functions.firestore.document('/users/{uid}').onDelete((event) => {
const userFriendsRef = getFriendsRef(firestore, uid);
userFriendsRef.get().then(snapshot => {
if (snapshot.docs.length === 0) {
console.log(`User has no friend list.`);
return;
} else {
snapshot.forEach(doc => {
// call some func using doc.id
});
}
}
}
};
function getFriendsRef(firestore, uid) {
return firestore.doc(`users/${uid}`).collection('friends');
}
Give it a try to fix your code from
db.collection('users').doc(currentUser.uid).collection('roles')
to
db.doc(`users/${currentUser.uid}`).collection('roles')
It is not clear what you are doing with the rol and status variables. You have declared them as though you are storing a single value, yet you are returning an array of roles and iterating through them.
With regards to getting the results, if your browser supports ES6, then you could do the following:
let userRef1 = db.collection(`users/${currentUser.uid}/roles`)
let cont = 0
let rol;
let rolStatus;
return userRef1.get()
.then(querySnapshot => {
// Check if there is data
if(!querySnapshot.empty) {
// Create an array containing only the document data
querySnapshot = querySnapshot.map(documentSnapshot => documentSnapshot.data());
querySnapshot.forEach(doc => {
let {rol, status} = doc;
console.log(`rol: ${rol} - status: ${status}`);
});
} else {
console.log('No data to show');
}
})
.catch(err => {
console.error(err);
});
Please note: I've only tested this with the Node SDK
// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyDNdWutrJ3Axpm-8ngNhzkzcw1g3QvkeFM",
authDomain: "books-7bd8b.firebaseapp.com",
databaseURL: "https://books-7bd8b.firebaseio.com",
projectId: "books-7bd8b",
storageBucket: "books-7bd8b.appspot.com",
messagingSenderId: "385706228283",
appId: "1:385706228283:web:a3c2c9585dd74d54693a1e",
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore();
export default firebase;
You should check if it always exists before doing your logic:
userRef1.get().then(function(querySnapshot) {
if(querySnapshot)
{
querySnapshot.forEach(function(doc) {
...you thing
}
})