node.js: firebase snapshot return null - javascript

I'm using firebase functions to run the code for my flutter app. That sends a push notification to my app. I want to get the token. But I'm getting null value at snap.val(). Here how my code looks like:
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
var db = admin.database();
exports.CreateTicket = functions.firestore
.document('tickets/{username}')
.onCreate((snapshot, context) => {
console.log(snapshot.data().clientUid);// this one working fine.
var ref = db.ref("token/BX3jXKVpOkRa80SIKb7jPwfbU0c2/");
ref.once("value", (snap) => {
console.log(snap.val()); // this one getting null,
});
});

Your code is querying Realtime Database, but the screenshot here is showing Firestore. These are completely different database systems. Your database query is simply finding nothing, because there is no data at the location of your query.
You will have to write your code using the Firestore APIs for nodejs to read the document you have shown here.

Related

TypeError: change.after.val is not a function firebase

Hi there I am trying to read changes in my firestore database
'use stricts'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
require('dotenv').config();
admin.initializeApp(functions.config().firebase);
exports.sendOrderCompletionEmail = functions.firestore.document('/service-requests/{req_id}')
.onUpdate((change, context) => {
const req = context.params.req_id;
const sts = change.after.val(); //Error on this line
console.log(sts);
});
I am getting this error
TypeError: change.after.val is not a function
I want to read changes in my document and return the field value which is changed
Since you are triggering your Cloud Function by the update of a Firestore document, you need to do
const sts = change.after.data();
See the doc for more details.
As a matter of fact we use the val() method for Cloud Functions triggered by a Realtime Database event.
Firebase offers two NoSQL database solutions: Cloud Firestore and the Realtime Database. See this doc for more details.

Firebase function not being triggered when data base is written to

My database is structured as follows Collection("Message").Document("message")
But in reality, I want any change in the database's main collection to be monitored—when a document is added. I added the message document because I thought that maybe the function wasn't being called since my documents are the auto-generated ones. However, the problem persists...
Just for background I am an iOS developer, so perhaps I am doing something wrong here:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendPushNotifications = functions.database.ref('/Messages/{message}').onCreate((snapshot,context) => {
console.log(snapshot);
console.log(context);
var topic = "/topics/sentMessages";
var payload = {
data: {
message : 'You recieved a new message!'
}
}
return admin.messaging().sendToTopic(topic,payload).then((response) => {
return response;
})
})
For additional background: The application receives push notifications fine when using the console whether it be directly to the testing device or using topics. This problem is strictly when writing to firebase Firestore...
When you said "Collection("Message").Document("message")" that suggested to me that you're using Firestore as your database. However, your function is targeting changes to Realtime Database, which is a completely different thing. functions.database builds function for Realtime Database. functions.firestore builds functions for Firestore. You will want to read the documentation on Firetore triggers to learn how to write them.

Get Every Document from inside a Users Collection Firebase

I have written a Firebase cloud function in which I want to get every users internal collection called 'numbers' and read each document out of that collection to do some comparisons.
Any idea how to do this?
I am pretty new to firebase and for some reason the database navigation commands are just not sticking with me very well.
I have tried a handful of commands with no success
const snapshot = functions.database.collection('users').collection('numbers').get()
let sfRef = db.collection('users');
sfRef.getCollections().then(collections => {
collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
});
Here is a loose cloud code infastructure
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
export const prize1 = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
const users = functions.database.ref('/users/numbers')
console.log("")
return null;
});
I feel like I have a good idea of how to do it, but the syntax is holding me back.
The collection of users. Go through each document in here, i.e. each user.
In each user go to the collection called numbers.
In the collection called numbers go through each document and find the numbers field to do logic/comparisons with.
Hopefully this can help you understand the way my database is ordered.
You could try it like this:
let usersRef = db.collection('users');
let allUsers = usersRef.get();
.then(userSnapshot => {
userSnapshot.forEach(userDoc => {
userDoc.ref.collection('numbers').get().then(numSnapshot => {
numSnapshot.forEach(numDoc => {
console.log(numDoc.data().numbers);
// here you got your numbers document with the numbers field
});
});
});
})
.catch((error) => {
console.log("Error getting document: ", error);
});
For more information you can look here and here.
You can't use functions for accessing the database. What you've defined as functions is for building triggers that respond to events. If you want to get data from Cloud Firestore, you should be using the Firebase Admin SDK via your admin instead. It might also help if you look through the official samples.
I will also point out that your code samples appear to be split between accessing Cloud Firestore and Realtime Database, which are different database products. Your screenshot shows Firestore, so ignore any APIs for Realtime Database.

How to update or set property of firestore document after .onCreate cloud function trigger

I'm currently trying to integrate Stripe with my Firebase's Cloud Firestore db through using Cloud Functions for Firebase. The onCreate trigger is happening correctly but I also want it to update or set a specific field called "customer_id" into the right document in my Users collection. I think something is a little off about how I write my function since I'm not the most experienced with javascript.
I've also tried
return admin.firestore().ref(`Users/${user.uid}/customer_id`).set(customer.id);
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
//const logging = require('#google-cloud/logging')();
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';
// When a user is created, register them with Stripe
exports.createStripeCustomer = functions.auth.user().onCreate((user) => {
return stripe.customers.create({
email: user.email,
}).then((customer) => {
return admin.firestore().collection("Users").doc(user.uid).update({"customer_id": customer.id})
});
});
Customer gets created with Stripe no problem but the "customter_id" field is not getting updated on the Firestore db.
Print screen of the database:
Print screen of the error log:
As said in the comments, from the print screen of the error log, the code you have deployed does not correspond to the code you are referencing to in your question.
The code in your question looks correct.

Firebase HTTP Trigger Cloud Function to change users' values in realtime database

So I have written code which should change a certain value in the database. I would use cron-jobs to trigger it in every 24h, but there is something wrong with my code.
const functions = require('firebase-functions');
exports.resetPicksStatus = functions.https.onRequest((req, res) => {
.ref('/users/{userId}')
.onWrite(event => {
const status = event.data.val()
if (status.resetted) {
return true
}
console.log("Resetting status for " + event.paramas.userId)
status.resetted = true
status.picksDone = resetToNil(status.picksDone)
return event.data.ref.set(status)
})
})
function resetToNil(s) {
var resetValue = s
resetValue = resetValue.replace(/\b1\b/ig, "0")
return resetValue
}
It looks like you're trying to put a Realtime Database trigger inside your HTTP trigger, which won't have the outcome you're looking for. Instead of using a database trigger, use the Firebase Admin SDK to access the database from within the HTTP trigger.
In your code, add
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const ref = admin.database().ref();
And use ref to access the database.
Check out the Admin SDK documentation here.
Here are some samples of Cloud Functions, some of which show the Admin SDK.
Here's a video showing how to use the Admin SDK
Here's a video on timing Cloud Functions

Categories