How can I get the id of a inserted document firebase-admin - javascript

I am handling some documents with firebase realtime database. I need to delete a document that I don't have the access to read it client side via SDK. In order to do that I need to know what is the id, so I should store it in my db (mongo) and when I need to delete a document on firebase I just get it from my DB and the I delete it.
I took a look to this answer but it doesn't work for me.
I insert documents into my firebase DB with this method (server side using firebase-admin)
const writeNotification = (uid: string, notification: INotification) => {
const db = admin.database();
const notsRef = db.ref(`notifications/${uid}`);
notsRef.push({
..._.omit(notification, 'to'),
});
};
If I do notsRef.id I get undefined.
How can I get the ID of my document that I have just inserted?
p.s. my documents are organized like this:

The answer you are looking at is about Firestore and not Realtime Database that you are using. The Reference has a key property and not id:
console.log('New Key', notsRef.key)
// to get child node's key
const childNotesRef = notsRef.push({
..._.omit(notification, 'to'),
});
console.log(childNotesRef.key)

Related

Error when creating a new document inside a new subcollection in firestore

I am using the v9 Web SDK.
I have a collection called 'transactions-in' which keeps a record of every transaction into a cardano wallet.
From time to time my server will send a transaction in response to each transaction in this collection (such as sending an nft or refunding ADA) and I want to add these transactions into a subcollection on the relevant transaction document, so the structure looks like this:
collection: 'payments_in'
document: document ID
subcollection: 'related_transactions'
document: newly created document reference
This is the code I have to get the right path to the newly created document ref and upload some test data into the firebase emulator:
//1. Get current doc
const currentDoc = doc(db, 'payments_in', transactionId);
//2. Build refund database entry
//2A. Get collection from database (will create one if doesn't exist)
const newCollection = collection(currentDoc, 'related_transactions');
//2B. Get a new document from database within new collection
const newSubDoc = doc(newCollection);
//2C. Upload entry to database
await setDoc(newSubDoc, { test: 'test' });
When I log the path of newSubDoc I get this, so the path looks good (I think??): payments_in/kXK5pimm29nRhU4CohA6/related_transactions/NL11eYmsB4M9vHw6PI8X
However when I try to submit the entry using setDoc I get the following error message:
#firebase/firestore: Firestore (9.1.1): Connection GRPC stream error.
Code: 3 Message: 3 INVALID_ARGUMENT: Document name "projects//databases/(default)/documents/payments_in/kXK5pimm29nRhU4CohA6/related_transactions/tLoCiHUJaA2uYhxt7drb"
lacks a project id at index 9.
Does anyone see what I am doing wrong here?
Thanks
If you look at the path in the error message, it is missing a project ID after projects/: projects//databases/(default)/documents/payments_in/kXK5pimm29nRhU4CohA6/related_transactions/tLoCiHUJaA2uYhxt7drb. You might want to double check how you initialize db and whether your Firebase configuration is complete.

how to check if value exists in realtime database firebase

I have created a realtime database on firebase and having no issues adding and removing data in tables etc.
I currently have it setup like this:
So my goal is to check if a given value is inside my database currently.
for example, I would like to check if 'max' is currently a username in my database.
var data = db.ref('loginInfo/');
data.on('value', function(snapshot) {
_this.users = snapshot.val()
});
That is how I get all the values, it is saved into _this.users
(How do i check if a value is inside this object, i am making a login program)
if i console.log the object, this is what I see:
image
If you want to check if a child node exists under loginInfo where the username property has a value of max, you can use the following query for that:
var ref = db.ref('loginInfo/');
var query = ref.orderByChild('username').equalTo('max');
query.once('value', function(snapshot) {
console.log(snapshot.exists());
});
I'd also recommend reading the Firebase documentation on queries, as there are many more options.

Finding a specific field in firestore with an id

I know this is a very basic question, but I am new to reactjs and firebase. After two days I am giving up on searching for an answer myself.
I have a firestore database 'MusicList' containing several documents. Within these documents the field 'seperatedStrings' holds (you'll probably will be guessing it) artists and titles of songs.
image of the firestore database
How do I retrive the value a single field (in this example 'seperatedString') using the ID (in this example '5ajnHZ8YDaiYvTAvJ1ec'?
Whenever I am querying for this:
firestore().doc("MusicList/" + "5ajnHZ8YDaiYvTAvJ1ec").seperatedString
the console claims that it is "undefined" (That is a lie!), I'd expect 'Phil Upchurch Blackgold'
Thanks in advance.
You are not using Firebase queries correctly. If you want to fetch a document from a collection, you would do so like this:
firebase
.firestore()
.collection('MusicList')
.doc('5ajnHZ8YDaiYvTAvJ1ec')
.get()
.then(doc => {
if (doc && doc.exists) {
const { separatedString } = doc.data();
//use separatedString
}
});
Check out Firestore - Get A Document for more information.
Also, it would probably be better to structure your documents differently. You could have an artist and track field, and use doc.data().artist and doc.data().track respectively.

Add field to document using cloud functions

I wanted to make the id of each document as a field of that document so that I can store it inside the doc. here is the cloud function I created:
exports.assignPID = functions.database
.ref('/players/{playerId}')
.onCreate((snapshot,context)=>{
const playerId = context.params.playerId;
console.log("new player "+playerId);
// const data = snapshot.val();
return snapshot.ref.update({'pid': playerId})
})
this deploys without any errors but whenever I add a new document to the 'players' collection there is no change in the document whatsoever
In your question, you use the word "document" to describe your data, which is a Firestore concept, and you've tagged this question google-cloud-firestore. However, the code you've written is for Realtime Database, which is a completely different product. So it will never run in response to changes in Firestore.
When you declare a function with functions.database, that's means Realtime Database. Instead, you should declare a Firestore trigger with functions.firestore. Please read the linked documentation for information about how to do that.

Querying firebase database to retrieve user name

I am working on firebase for the first time. I am confused in querying the database. I have two objects on the database, one is the Auth and second one is the Chats. In Auths I have number of UID(user id) nodes, each of these nodes have their respective username. What I am trying to do is, I want to query that Auth object and get all the usernames which is equal to the one I take from a user through input box. In my sql it will be simple as SELECT * FROM auth WHERE username = userInputValue. I need same query like this, Below is what I have done so far.
var _firbaseDB = firebase.database(),
_firebaseAuthRef = _firbaseDB.ref("Auth/");
$("body").on("submit",".search-from",function(e){
e.preventDefault();
var ev = e.target,
_allUsers = $(ev).serializeArray()
_user = _allUsers[0].value;
_firebaseAuthRef.equalTo(_user).on("child_added",function(res){
console.log(res.val());
})
})
You were almost there. What's missing is that you need to specify which attribute you're querying on:
_firebaseAuthRef.orderByChild("n").equalTo(_user).on("child_‌​added",function(res)‌​{
console.log(res.val());
})
More info on the Firebase Database Documentation.

Categories

Resources