Please, I need your help to get the server timestamp from Firebase version 9.
I've tried to follow the same approach as for Firebase v8 : firebase.firestore.FieldValue.serverTimeStamp() but didn't work for version 9.
Is there any way to do the same thing in Firebase version 9 ?
It's discussed in the documentation. Just import serverTimestamp.
import { updateDoc, serverTimestamp } from "firebase/firestore";
const docRef = doc(db, 'objects', 'some-id');
// Update the timestamp field with the value from the server
const updateTimestamp = await updateDoc(docRef, {
timestamp: serverTimestamp()
});
If you get type error with other answers you can try this:
import { Timestamp} from '#firebase/firestore';
createdAt: Timestamp.fromDate(new Date())
import {serverTimestamp} from 'firebase/firestore';
Then simply change timestamp: firebase.firestore.FieldValue.serverTimestamp() to timestamp: serverTimestamp()
Firestore Database V9:
import { doc, updateDoc, serverTimestamp, getFirestore } from "firebase/firestore";
const db = getFirestore(app);
const docRef = doc(db, 'yourCollection', 'yourDocId');
await updateDoc(docRef, {
timestamp: serverTimestamp()
});
Firebase Realtime Database V9:
import { serverTimestamp, ref as fbRef, getDatabase, update } from 'firebase/database';
const db = getDatabase(app);
const yourUpdatedDoc = {
lastUpdated: serverTimestamp()
}
await update(
fbRef(db, `/yourDocLocation`), yourUpdatedDoc
);
If anyone is looking for an answer of this question
import { serverTimestamp } from 'firebase/firestore/lite';
lastSeen: serverTimestamp()
Related
I have config/firebase.ts:
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'
const firebaseAdminApp = initializeApp({
credential: cert({
privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}),
databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});
const firestore = getFirestore(firebaseAdminApp);
export default firestore
and when trying to upsert, I have:
import firestore from "../config/firebaseAdmin";
const upsertInstance = async (instance: Instance) => {
const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
return res
}
but I get:
Error: expected a function
What am I doing wrong?
Firebase Admin is not totally modular yet like the client SDK yet so you would have to use namespaced syntax. Admin SDK's Firestore instance won't work perfectly with client SDK functions. Try refactoring the code as shown below:
export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"
const upsertInstance = async (instance: Instance) => {
const res = await db.doc(`instances/${instance.uri}`).set(instance);
return res;
}
Checkout the documentation for more information.
I did manually set up the entire data into Firebase Firestore have been trying to retrieve the data as followed
import app, { db } from "./app";
import {
addDoc,
collection,
doc,
getDocs,
getFirestore,
limit,
orderBy,
query,
setDoc,
Timestamp,
} from "firebase/firestore";
export default async function getEvents() {
const db = getFirestore(app);
const first = collection(db, "Events");
const docSnap = await getDocs(first);
console.log(docSnap.data());
}
The thing over here is that the console throws an error saying that docSnap.data() is not a function
TypeError: docSnap.data is not a function
Yes apparently the mistake I did was that I need to specify the document before I get it's data, So the correct thing to do would be
console.log(docSnap.docs[0].data());
If you want all the data from all the elements maybe you can loop over them or just map them depending over your preference.
My js file is correctly entered in the DOM, I have initailized firebase in the firebase.js file. Why am I getting a
TypeError 'collection(...).doc is not a function' -
The collection query is taken directly from the firebase docs site, I don't understand how this could be a type error.. Any ideas?
import { app } from "./firebase";
import { getFirestore, doc, collection } from "firebase/firestore";
const db = getFirestore(app);
// get data
const docRef = collection(db, 'posts').doc('ARt1ctrEjweKEd4gmgCr');
await docRef.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
The doc() is top level function in Modular SDK and not a method on collection(). Try:
import { getFirestore, doc, getDoc } from "firebase/firestore";
// Creating DocumentReference
const docRef = doc(db, 'posts', 'ARt1ctrEjweKEd4gmgCr');
const docSnap = await getDoc(docRef);
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
Also checkout: Firestore: What's the pattern for adding new data in Web v9?
I've been trying to create a chat app using react and firebase just for practice since I wanted to try out Firebase, and although I'm able to print out the array of objects that I retrieved into the console, I can't seem to access those objects directly... For example:
if I code "console.log(testArray);" this is what displays in the console, which is all good
0: {name: 'JohnDoe', profile_image: 'imaginary image URL', date: it, message: 'This is my first message to Firebase!'}
but if I try console.log(testArray[0]); it displays undefined in the console
Here's my code
import Config from './config';
import { initializeApp } from "firebase/app";
import {
getFirestore,
addDoc,
getDocs,
collection,
query,
orderBy
} from "firebase/firestore";
function App() {
const firebaseApp = initializeApp(Config);
const firestore = getFirestore();
const chat_collection = collection(firestore, "chat");
const addData = () => {
addDoc(chat_collection, {
date: new Date(),
message: document.getElementById("message").value,
name: "JohnDoe",
profile_image: "imaginary image URL"
});
}
let testArray = [];
const readData = async () => {
const chatAppQuery = query(
collection(firestore, 'chat'),
orderBy('date')
);
const chatSnapshot = await getDocs(chatAppQuery);
chatSnapshot.forEach((message) => {
testArray.push({
name: message.data().name,
profile_image: message.data().profile_image,
date: message.data().date,
message: message.data().message
});
});
}
readData();
console.log(testArray);
console.log(testArray[0]);
My first time asking for help on here, I'd deeply appreciate it!
Since readData is an async function, you need to use await (or then() to wait for it results.
So:
await readData();
// 👆
console.log(testArray);
console.log(testArray[0]);
If you're in a context where you can't use async/await, you can also use then:
readData().then(() => {
// 👆
console.log(testArray);
console.log(testArray[0]);
})
Hello I am trying to configure react app with firebase and use firestore.
"firebase": "^9.1.3"
I followed the instructions given in official docs.
Here is my congig.js file.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: '****',
authDomain: '*****',
projectId: '*****',
storageBucket: '*****',
messagingSenderId: '****',
appId: '*****',
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
I am sure this gets initialized.
When I export it and use it in other file. collection is greyed out in vs code that means i am not using the import.
databaseservice.js
import { db } from './config';
import { collection, doc } from 'firebase/firestore';
export const getChapters = (scanId) => {
db.collection('somecollection')
.doc(scanId)
.get()
.then((doc) => {
if (doc.exists) {
console.log('Document data:', doc.data());
} else {
// doc.data() will be undefined in this case
console.log('No such document!');
}
})
.catch((error) => {
console.log('Error getting document:', error);
});
};
Error:TypeError: config__WEBPACK_IMPORTED_MODULE_0_.db.collection is not a function
I have tried with compat and lite versions. Getting the same issue.
This is v8/compat syntax:
db.collection('somecollection')
.doc(scanId)
.get()
.then((doc) => {
In v9/modular syntax, the equivalent is:
getDoc(doc(db, 'somecollection', scanId))
.then((doc) => {
For converting this type of thing, I find it easiest to keep the Firebase documentation and upgrade guide handy.
Firebase have changed their API to new modular syntax in version 9. You are using old syntax from version 8. You can read more about this and find instructions on upgrading your code here: https://firebase.google.com/docs/web/modular-upgrade
Also, everywhere in Firebase documentation, they now have 2 separate examples: one for old syntax, one or new modular syntax: https://firebase.google.com/docs/firestore/query-data/get-data