I'm trying to add two related items to my Firebase database. I want to push one item, then get that item's newly created key and use it as the key for the second item in a different tree. I've tried querying the database to get the last key created and using it as the key for the second push, but it's still just generating a new key for it. Here's the code that I'm using:
save: function() {
if (this.$.document.isNew && (this.editableCard.title || this.editableCard.body)) {
return this.$.document.save(this.cardsPath).then(function() {
this.$.document.reset();
var sceneRef = firebase.database().ref().child(this.cardsPath);
var scene = sceneRef.orderByKey().limitToLast(1);
var sceneKey = scene.key;
this.$.document.save('/documents/', sceneKey);
}.bind(this));
}
return Promise.resolve();
}
(I'm using Polymer, and my starting point is the note-app demo for Polymerfire).
Any ideas on how I can retrieve the new key of the first push and use it for the second push? Thanks!
EDIT
I found the answer in Firebase's documentation for Reading and Writing to the database for Web. Link
push() returns a DatabaseReference immediately. You can ask that reference what its key is, using getKey(), then use that string to update another location in your database.
You can access the key property on the original database reference and use that as the key for the second one, like so:
let firstObjRef = firebase.database().ref('/first/path/).push(firstObj, (error) => {
videoObj["roomUploadedTo"] = this.roomName;
var updateObj = {};
updateObj[videoObjRef.key] = videoObj;
firebase.database().ref('/second/path/').update(updateObj).then( (e) => {
console.log('update went through. booyah! ' + e);
})
Related
I switch to firebase 9 and want to achieve following
customers
-MomOdRNzkqr9vDk_MmE:"ptwXJ7JRAASFgd3KoS2fQyQhyV613"
-Myb3b_2W-7FTlsZvXCO:"QZOQ43DGYwfu4djlZ5EjEVksOr53"
I am trying the following
const customerSelectedRef = ref(db,`/serviceProvider/${user1.uid}/moneyCollector/customers`);
const customerSelectedRefPush = push(customerSelectedRef);
set(customerSelectedRefPush, customerSelected); // not wanted to use {customerSelected} which gives key value pair under push id
How could add value directly to push id?
The old method was
firebase
.database()
.ref(`/serviceProvider/${user1.uid}/moneyCollector/customers`)
.push(customerSelected)
.then(() => {
console.log("Data set.moneyCollector cutomer added");
checkdubArray = [];
});
Where push id acts as key for customerSelected
and I try to get same result in firebase 9.
Dont want the result which I have marked as cross
You can pass the string value directly in push() along with the DatabaseReference as shown below:
const customerSelectedRef = ref(db,`/service/${user1.uid}/Collector/customers`);
await push(customerSelectedRef , "string_value") // Not object
The result would be:
not able to check the unique values log showing all values getting
added to the array
.
var moveToReady = [];
var topLinesRecords = new GlideRecord('x_snc_ms_dynamics_d365_queue');
topLinesRecords.addEncodedQuery('root_element_sys_id=03133e1a1bfe6410f8ca0e16624bcba7');
topLinesRecords.orderByDesc('sys_created_on');
topLinesRecords.query();
while(topLinesRecords.next()){
gs.info(' first record : ' + topLinesRecords.number);
if(moveToReady.indexOf(topLinesRecords.getValue('object_sys_id')) == -1){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
gs.info('array. : ' + moveToReady);
updateRecordtoFail(topLinesRecords);
}
You can use the Set structure from ES6 to make your code faster and more readable:
// Create Set
this.items = new Set();
add(item) {
this.items.add(item);
// Set to array
console.log([...this.items]);
}
you may use array.includes
if (!moveToReady.includes(topLinesRecords.getValue('object_sys_id'))){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
So, some tips to get unique values on ServiceNow:
-GlideRecord has a "getUniqueValue" method
(URL: https://docs.servicenow.com/bundle/paris-platform-administration/page/administer/table-administration/concept/c_UniqueRecordIdentifier.html)
-You can search on your Script Includes a OOB method/function to get only unique values. Search for "utils". Every instance has this, maybe "ArrayUtils".
Hope this information helped!
First of all will be easier if you check the Firebase realtime database image:
So with my code I create some "practicas" with an id (152648... in this case) and then, inside that object I create a list of "grupos" (groups). The problem comes here, to do this I use .push(), so Firebase creates a list inside that firebase main node, but the thing is that the 'key' it uses is random, so then, I want to access to the last step called "alumnos", but as I don't know the previous key I can't access there. I tried to use an ID to push the object but it adds the ID and then the key.
My code:
//don't take care about what is values[], grupoList[] and so on
//I just take values from a checkbox on the HTML and I send them to the 'grupo' value of the object 'practica'
addGroup(){
let y=0;
for(let i=0; i<this.values.length; i++){
if(this.values[i] == true){
this.grupoList[y] = this.profiles[i];
y++;
}
}
this.grupo.alumnos = this.grupoList;
this.practica.grupo = this.grupo;
this.practicaService.anyadirGrupos(this.practica);
this.navCtrl.setRoot(VerGruposPage, {'data': this.practica});
}
PracticaService:
//Here is where I work with firebase adding the 'grupo'
public anyadirGrupos(practica){
this.afDB.database.ref('practicas/' + practica.id + '/grupos/').push(practica.grupo);
}
//to access the node 'alumnos' (it doesn't work)
public getAlumnos(practica){
return this.afDB.list('practicas/' + practica.id +'/grupos/' + '../alumnos/')
}
Any idea to access to the last step without knowing the previous one?
You can have two different possible approaches:
1/ Write the "sub-grupos" without an extra key
Which means having a database structure like this:
- practicas
-idPracticas
-grupos
-alumnos
-0 ....
-1 ......
-anotherGroupName
-0 ....
-1 ......
To do that you should use set() instead of push()
2/ Keep your structure and loop over the different child nodes
db.ref('practicas/' + practica.id + '/grupos/').orderByKey().once('value').then(function(snapshot) {
console.log(snapshot.val());
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val());
console.log(childSnapshot.val().alumnos[0]);
console.log(childSnapshot.val().alumnos[1]);
});
});
I have trawled the net and stackoverflow for an answer to this question.
How does one retrieve a value from a dynamic key which is also nested in localstorage.
I have tried numerous examples and seem to be getting nowhere.
I knwo a loop is required to perform the task but which type.
How do I get the 'uniqid' value which has the nested dynamic key SCI-4 from localstorage which reads:
simpleCart_items:{"SCI-4":{"quantity":4,"id":"SCI-4","price":8,"name":"12 fried chicken","flavours":"cola","code":"1001","cartid":"561","uniqid":"592dcd08b5fcc"}}
This allows me to view localstorage.
var obj = localStorage;
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
How do I iterate to get any value?
The difference in this question is that I seek to get the value from a nested key that has a dynamic value. If the key is not known how does one pull the value? What should the loop look like?
After a good nights sleep.
I am able to make headway. Thank you for pointing me in the right direction guys.
There are many opinions and ways to do some of these functions which got confusing.
localStorage needed to be accessed properly as I show below.
The issue is mostly resolved with:
var obj = JSON.parse(localStorage.simpleCart_items);
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if (val === "quantity")
{
//logic here
console.log(obj[key][val]);
}
});
});
think this is what your're looking for, :)
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if(val === "uniqid")
{
//logic here
console.log(obj[key][val]);
}
});
});
If you just store your structure as a single value for a single key, it's pretty easy to extract it later.
// How do I get the 'uniqid' value which has the nested dynamic key SCI-4 from localstorage which reads:
// This is our simulated result from pulling from localStorage
var lsString = `{
"simpleCart_items": {
"SCI-4": {
"quantity":4,
"id":"SCI-4",
"price":8,
"name":"12 fried chicken",
"flavours":"cola",
"code":"1001",
"cartid":"561",
"uniqid":"592dcd08b5fcc"
}
}
}`;
// First, remember that localStorage stores strings, so we must parse the string
// back into an object:
var lsObj = JSON.parse(lsString);
var keyName = Object.keys(lsObj.simpleCart_items).toString();
// Now, we can go directly to the property we want:
console.log(lsObj.simpleCart_items[keyName].uniqid);
I am currently making an app using Firebase.
It is one of those bulletin boards that can be seen anywhere on the web.
But there was one problem.
This is a matter of date sorting.
I want to look at the recent date first, but I always see only the data I created first.
postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);
})
result - >hello1496941142093
My firebase tree
My code is the same as above.
How can I check my recent posts first?
How Do I order reverse of firebase database?
The Firebase Database will always return results in ascending order. There is no way to reverse them.
There are two common workaround for this:
Let the database do the filtering, but then reverse the results client-side.
Add an inverted value to the database, and use that for querying.
These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:
Display posts in descending posted order
Sort firebase data in descending order using negative timestamp
firebase sort reverse order
Is it possible to reverse a Firebase list?
many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript
You can simply make a function to reverse the object and then traversing it.
function reverseObject(object) {
var newObject = {};
var keys = [];
for (var key in object) {
keys.push(key);
}
for (var i = keys.length - 1; i >= 0; i--) {
var value = object[keys[i]];
newObject[keys[i]]= value;
}
return newObject;
}
This is how I solved it:
First I made a query in my service where I filter by date in milliseconds:
getImages (): Observable<Image[]> {
this.imageCollection = this.asf.collection<Image>('/images', ref => ref.orderBy('time').startAt(1528445969388).endAt(9999999999999));
this.images = this.imageCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Image;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
return this.images;
}
Then to get the newest date first I added this to my component where I call the method from my service:
let date = new Date;
let time = 9999999999999 - date.getTime();
console.log(time);
I pass the time let as the date. Since a newer date will be a bigger number to deduct from the 9999999999999, the newest date will turn up first in my query inside my service.
Hope this solved it for you
If you want to display it in the front end, I suggest that after you retrieve the data, use the reverse() function of JavaScript.
Example:
let result = postRef
.orderByChild("createData")
.startAt(reverseDate)
.limitToFirst(1)
.on("child_added", data => {
console.log(data.val().name + data.val().createData);
});
result.reverse();
Ive ended changing how I create my list on the frontend part.
was
posts.add(post);
changed to
posts.insert(0, post);
You could use a method where you save the same or alternate child with a negative value and then parse it.
postRef.orderByChild('createData').orderByChild('createData').on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);})
Far more easier is just use Swift's reversed():
https://developer.apple.com/documentation/swift/array/1690025-reversed
https://developer.apple.com/documentation/swift/reversedcollection
let decodedIds = try DTDecoder().decode([String].self, from: value)
// we reverse it, because we want most recent orders at the top
let reversedDecodedIds = decodedIds.reversed().map {$0}
orderBy("timestamp", "desc")
I think you can give a second argument name "desc".
It worked for me