How to get Key / Id of the data written into Firebase? - javascript

I have a application which stores employee records, it stores the employees ID, but also needs each employee to have a local ID, I want to use the ID generated by Firebase when we push data onto the db using push() function as the internal ID for each employee. This is required for change management.
My code:
function submit()
{
var dsRef=new Firebase("https://dataretrievaltest-28983.firebaseio.com/EmployeeDB/EInfo");
var name=document.getElementById('Name').value;
var eid=document.getElementById('EID').value;
var email=document.getElementById('Email').value;
dsRef
.push(
{
Name:name,
EID: eid,
Email: email,
}
);
var pushid=dsRef.name;
console.log("name:"+pushid);
console.log(name);
console.log(eid);
console.log(email);
}
Output of the above code:
name:function (){S("Firebase.name() being deprecated. Please use Firebase.key() instead.");D("Firebase.name",0,0,arguments.length);return this.key()}
savekey.html:104 Djoko
savekey.html:105 0143
savekey.html:106 Djoko#dept.com
Have used Key in place of name as name is deprecated but did not get the key, instead it returns a function.
The code with key in place of name
var pushid=dsRef.key;
console.log("name:"+pushid);
Output after change:
name:function (){D("Firebase.key",0,0,arguments.length);return this.path.e()?null:me(this.path)}
savekey.html:104 Caroline
savekey.html:105 0192
savekey.html:106 caroline#dept.com
I need the Keys viz -Kb5... : which is seen in below Json
"EInfo" : {
"-Kb5UunYfq-8zd_Jc2Nd" : {
"EID" : "0134",
"Email" : "Parker#dept.com",
"Name" : "Parker"
},
"-Kb5V9xHhzVix6BNRM78" : {
"EID" : "1024",
"Email" : "sanchez#dept.com",
"Name" : "sanchez"
}
}
The available properties(key/name) don't give the required output. Please let me know how to retrieve the key and if I am missing anything.
Also tried
var pushid=dsRef.child("EInfo").push().key;
console.log("name:"+pushid);
it did not give the desired result.
name:function (){D("Firebase.key",0,0,arguments.length);return this.path.e()?null:me(this.path)}
savekey.html:104 camila
savekey.html:105 0172
savekey.html:106 camila#dept.com

You're using Firebase SDK version 2.x, but are mixing in syntax from version 3.x. For Firebase 2.x, the syntax to get the key is:
var pushid=dsRef.key();
console.log("name:"+pushid);
If you're creating this app now, you should really be using Firebase 3.x SDKs, in which case the syntax would indeed be dsRef.key (without parentheses).
Update
You seem to be looking for the key of the item that you just created with push(). You can get that by assigning the result from push to a variable:
var newRef = dsRef.push({
Name:name,
EID: eid,
Email: email,
});
console.log(newRef.key()); // or newRef.key when using SDK version 3.x

Related

Retrieve data from Firebase using Google Apps Script

I'm developing a Google Spreadsheet to manage reservations for a hotel. It has two main tabs. One of them is used to make the reservations and the other one is used to make queries to the reservations already made. I managed to make it work just fine with the built-in tools of google apps script using a tab as database.
I'm trying to export my data to a Firebase database, but I cannot find how to fetch some information I need. My data is stored using a code generated using the date of the reservation as integer format + the name of the person without spaces. This is the JSON generated by firebase:
{
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
}
}
My question is: let's suppose I want to know all the reservations made for the day 01/March/2021, what is the code for me to look inside the objects and then, if they match my search, get the info I need?
I converted the JSON to an array of objects, then filtered by date. Added the console logs to check if everything is right. You can see the logs when you go to view -> executions in your script. Click on the function execution to see the logged objects.
function myFunction() {
var a ={
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
},
"44256002ÍcaroNovodeOliveira" : {
"code" : 44256002,
"date" : "2021-04-01T03:00:00.000Z",
"name" : "Ícaro Dovo de Oliveira"
}
};
var values_a = Object.values(a);
var keys_a = Object.keys(a);
var array_a = keys_a.map((item, index)=> {return {"key": item, "values": values_a[index]};});
console.log(array_a);
var filter_date = "2021-03-01T03:00:00.000Z";
var filtered_a=array_a.filter(item => {return item.values.date === filter_date;})
console.log(filtered_a);
}
Thank you for your help! But my point was actually a little bit different, maybe I wasn't so clear.
While trying to explain it to you, I found the answer to my question. It was right under my nose this whole time and I didn't notice it. Here is the solution I needed:
First, I have to assign a rule to my firebase telling it what element I will be working on, so if I want to find reservations based on the date, it would look like this:
{
"rules": {
".read": true,
".write": true,
".indexOn":["date"]
}
}
Then, back to my script, it will be like:
function getReservations() {
var ss = SpreadsheetApp.getActive().getSheetByName('Search');
var date = ss.getRange('C11').getValue();
var firebaseUrl = "https://script-examples.firebaseio.com/";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var queryParameters = {orderBy:"date", equalTo: date};
var data = base.getData("", queryParameters);
for(var i in data) {
Logger.log(data[i].code, data[i].name, data[i].date);
}
}
The log retrieves:
[20-12-08 11:30:33:696 BRT] 44256001 Larissa Meimberg Baraldi 2021-03-01T03:00:00.000Z
[20-12-08 11:30:33:698 BRT] 44256001 Ícaro Novo de Oliveira 2021-03-01T03:00:00.000Z
This information was described on the documentation here:
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials/read-and-write-data-in-firebase-from-apps-script
I think I got a little overwhelmed with the amount of information I got and skipped this part of the tutorial.
Thank you so much for your time and help.

Google Sheets + Monday.com API - Change column value

I managed to connect the Monday.com API with google sheets using Scripts and create a new item in my board, however, I can only insert the item name, how can I insert a value in my column.
Code example:
function Create_Line()
{
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("tests");
var values = sh.getDataRange().getValues();
var mondayAPIkey = "API_KEY"
for(var i=1;i<values.length;i++)
{
if(values[i][7]=="")
{
var query = "mutation($board:Int!, $name:String!,$colvals:JSON!){create_item(board_id:$board, item_name:$name, column_values:$colvals){id}}";
var variables = {
"board" : "board_id",
"name" : values[i][0], //where column A has the name I want for the item
"colvals": JSON.stringify({ "column_id": "Coluna 1", "value": "Done"}) //calling the now formatted date variable
};
var pulseID = JSON.parse(makeAPICall(mondayAPIkey, query, variables)).data.create_item.id;
sh.getRange(i+1, 8).setValue(pulseID)
}
}
}
EDIT: To explain the question in a better way, the result that I'm looking for is this:
The script runs through the entire google sheets list and creates the lines on Monday.com, the problem is that I can not fill the column value
The column values argument you're passing to the monday.com API is in the wrong format. I cannot find your column ID in your original post, so I'm going to assume it's 'coluna_1'.
Try changing your variables to this:
var variables = {
"board" : YOUR_BOARD_ID,
"name" : values[i][0],
"colvals" : JSON.stringify({"coluna_1" : "Done"})
}
According to the official monday API Quickstart:
Our GraphQL schema defines a set of column values as a JSON string (key-value pairs). The keys of the column_values object must be column IDs, and the values must be structured depending on the type of the column.
You can find the column ID by enabling developer mode, as described in this article.
The value depends on the column type in monday.com. You can see a list of columns supported by the monday.com API here: API Documentation

Create Bitcoin SV transaction with moneybutton/bsv js library

I want to create a raw transaction using the BSV JavaScript library from MoneyButton (https://github.com/moneybutton/bsv/)
When creating a bitcoin Satoshi Vision (BSV) transaction I always get an error.
'node_modules/bsv/lib/encoding/base58check.js:58 if (csum.toString('hex') !== hash4.toString('hex')) { throw new Error('Checksum mismatch') }'
I have also tried to generate the transaction using the JavaScript BitbossIO/keyring library and I was also not able to generate a raw transaction.
I don't know which part I'm getting wrong.
const bsv = require('bsv');
var privateKey = new bsv.PrivateKey.fromWIF('pL3yyzZEc96qU8PUyAtk3TBzyosTVGhA1eMWc6icZzS2ZKTnHGuAh');
var utxo = new bsv.UnspentOutput({
"txId" : "600fee0e6eca8eb19c40f5bfae5871446e617d44c39a3ad44782c571dbf59650",
"outputIndex" : 1,
"address" : "12cyVmfJVwkBA4MUSUDarUL2jXiM98JEoe",
"script" : "76a91411c5d84f5eca47921b0b92042de543f209c301a188ac",
"satoshis" : 6691
});
var transaction = new bsv.Transaction()
console.log(transaction)
.from(utxo)
.to('1PM2zxJArgHFxqYkrFqN7aKQV8nfnEGA56', 5000)
.change('1PM2zxJArgHFxqYkrFqN7aKQV8nfnEGA56')
.sign(privateKey);
console.log(transaction.toString());´
I wish I could generate a transaction. Also, please find above the private key to the transaction. You may use the 10cents, but please help me with the transaction. ;)
I believe the key you're using is incorrect, as that's the line that's causing the error because the format is incorrect.
Make sure you're using the correct WIF key.
It's a while ago. Found it when I was searching for building transactions.
Yes, the key is incorrect. I have figured out which is the correct key, and processed the transaction.
Here is the code with the correct key:
"use strict";
const bsv = require("bsv");
//const privateKey = new bsv.PrivateKey.fromWIF('pL3yyzZEc96qU8PUyAtk3TBzyosTVGhA1eMWc6icZzS2ZKTnHGuAh');
const privateKey = bsv.PrivateKey.fromWIF('L3yyzZEc96qU8PUyAtk3TBzyosTVGhA1eMWc6icZzS2ZKTnHGuAh');
const utxo = new bsv.Transaction.UnspentOutput({
"txId" : "600fee0e6eca8eb19c40f5bfae5871446e617d44c39a3ad44782c571dbf59650",
"outputIndex" : 1,
"address" : "12cyVmfJVwkBA4MUSUDarUL2jXiM98JEoe",
"script" : "76a91411c5d84f5eca47921b0b92042de543f209c301a188ac",
"satoshis" : 6691
});
const transaction = new bsv.Transaction()
.from(utxo)
.to('1PM2zxJArgHFxqYkrFqN7aKQV8nfnEGA56', 5000)
.change('1PM2zxJArgHFxqYkrFqN7aKQV8nfnEGA56')
.sign(privateKey);
console.log(transaction.toString());

How to get values from a field in Mongo, using its Java Driver (3.5.0)

I'm using MongoDB in javascript, and have been using Mongo's Java Driver. (It's because it is in JAR format and I'm using Mirth Connect). The thing is, I'm trying to use fields from another collection and bring informtation to the new collection. From what I've read, the filter from the Java Driver should return a DBCursor. I'm not good at javascript, and haven't figured out how to get a value from a field, from a query I made already.
I'm using this to make the query:
var uri = new Packages.com.mongodb.MongoClientURI("mongodb://usr:pwd#localhost:27017/admin");
var mongoClient = new Packages.com.mongodb.MongoClient(uri);
var database = mongoClient.getDatabase("mydb");
var collection = database.getCollection("mycollection");
var person = collection.findOne(com.mongodb.client.model.Filters.eq("person.id", id));
For example, I would like to have the name of the person I associated with the ID. Any help of how can I get it, would be very appreciated.
Also the JSON from the collection is something like this:
{"patient" : {
"id": 1234,
"first_name": "Peter",
"last_name": "Parker",
},
"other_stuff": ...
}
Try below code with find one ( find + first ) with dot notation to access first name for patient.
var uri = new Packages.com.mongodb.MongoClientURI("mongodb://usr:pwd#localhost:27017/admin");
var mongoClient = new Packages.com.mongodb.MongoClient(uri);
var database = mongoClient.getDatabase("mydb");
var collection = database.getCollection("mycollection");
var personName = collection.find(com.mongodb.client.model.Filters.eq("person.‌​id", id)).first().get("patient.first_name")

How do I to target a single value in firebase database?

I'm having trouble figuring out how to target a single object in the firebase database. For example, I want to have a specific word/definition shown when I click an index card. I'm using this to store the data:
wordVal = $("#word").val();
defVal = $("#def").val();
data = firebase.database().ref("indexCards");
data.push( { 'word': wordVal, 'definition': defVal } );
and this to retrieve it:
data.on("child_added", function(snapshot){
console.log(snapshot.val().word);
console.log(snapshot.val().definition);
});
This gives me the whole list of words and definitions. I want to refer to specific words and specific definitions, separately. The docs say that I can reference the specific values by doing this - firebase.database().ref("child/path").
But my question is...how can I reference the path when the parents are those random numbers and letters (see below)? I know that these are unique IDs generated by firebase, but I don't know how to access them like I'd access ordinary objects.
{
"-KQIOHLNsruyrrnAhqis" : {
"definition" : "person, place, thing",
"word" : "noun"
},
"-KQIOO7Wtp2d5v2VorqL" : {
"definition" : "device for photos",
"word" : "camera"
},
"-KQISp4WMnjABxQayToD" : {
"definition" : "circus act",
"word" : "clown"
},
"-KQITC9W1lapBkMyiL7n" : {
"definition" : "device used for cutting",
"word" : "scissors"
}
}
You can use a query like this:
data = firebase.database().ref('indexCards').orderByChild('word').equalTo('noun')
It is self-explanatory, we get reference to indexCards where value of key word is equal noun, so it will return object with key -KQHZ3xCHTQjuTvonSwj
Link to Firebase docs: Retrieve data - Sorting and Filtering data
You need to put the initial push into an object then call the object later. ie
To PUSH data:
firebase.database().ref().push( { 'word': wordVal, 'definition': defVal } )
To UPDATE data or call it later:
firebase.database().ref("indexCards").set({})
or in this case:
data.set({})

Categories

Resources