Angularfire - Retrieve unique ID of all objects in array - javascript

I have two different array in Firebase : The first is "General post" and the second is "The favorite post by user".
When user want put a post in favorite, I copy all data of this unique post in "General post" to "The favorite post by user" with the same ID.
The problem is when the post name is changed, he is changed only in "General post" and stay the same in "The favorite post by user".
So I try to retrieve only post name in "General post" like this :
var postRef = new Firebase("https://myapp.firebaseio.com/posts")
var userFavoriteRef = userRef.child($scope.user_id).child("favorite_posts")
$scope.favoritePosts = $firebaseArray(userFavoriteRef)
var favoritePosts = $firebaseArray(userFavoriteRef)
userFavoriteRef.once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key()
$scope.key = childSnapshot.key()
postRef.child($scope.key).child("name").once('value', function(snap) {
console.log(snap.val())
$scope.name = snap.val()
})
})
})
But I have "null" in my console log... And it's dont work ...
Maybe my logic is false ...
What do you think ? Pending read you ... Thanks !

Might be better to take a different approach to storing the data. Instead of having two copies of the data, just have one with a unique id. Then on each individual user, you can reference the unique ids of the posts they have favorited. This allows you to be able to update the data only in the one location.
For example, you could use a data structure like:
myFirebase
- users
-user1
-user2
-user3
-favorites
-unique2 (reference to post, not the actual post)
-unique4
- posts
-unique1
-unique2
-unique3
-unique4
So, you just have one copy of the data and then reference it from your user objects to retrieve what you are looking for. And changes to the post are reflected everywhere that references that post.

Related

Updating Query in Firestore

I am new to Firestore, need some help on firestore update.
I have following structure and wants to update "employee name" property. Not sure how to select and update.
Department:[
Name: Accounts
Employee:[
{Name :David,
Age :25},
{Name:Paul,
Age:27}
]
]
Here is what I was trying to do:
let depempCollectionRef = admin.firestore().collection('DepEmployee').doc('depempid')
depempCollectionRef.Department.Employee
.update({ name: 'Scott' },{merge:true})
.then(function() { console.log("Document successfully updated!"); })
Employee is just an embedded data structure in your Firestore document ā€“ so you can't address it through the reference directly. As far as Firestore is concerned, Employee is just an attribute on the Department document as Name is.
Before I propose a solution, let me point out two things:
If using update, you don't need {merge: true}. You use {merge: true} together with set to get an update-like behavior, if the document already exists.
I wouldn't use an Array of employees. It might make more sense to store the employees in their own collection in Firestore and then just list their reference IDs (= foreign keys) here. As a general rule of thumb: try to keep your data structure flat. Also use Arrays only, if you need to maintain a certain order of items.
A) If you have a separate collection for employees, updating the name is as easy as:
employeeCollection.doc('101').update({name: 'Scott'})
B) If you want to store employee data within your department document, I would still store them as a map with IDs (instead of an Array) and then access them with dot notation:
Department:[
Name: Accounts
Employees:{
101: {
Name :David,
Age :25
},
102: {
Name:Paul,
Age:27
}
}
]
depempCollectionRef.Department
.set({ ['101.name']: 'Scott' }, {merge:true})
C) And if you really want to store the data embedded in an Array, I believe you have to read and update the whole Array (not sure, if there is a better solution):
const employeesSnap = await depempCollectionRef.Department.get()
const updatedEmployees = changeNameOfScottInArray()
depempCollectionRef.Department
.update({ 'Employees': updatedEmployees })
I didn't test this code, but I hope you get the gist of it!
I'd recommend you flatten your data structure by creating a separate Employee collection and then just referencing them by their foreign key in your department (solution A).

How to access firebase db sub object elements?

My firebase db structure is given below,
users
fb-user-key1
user1-details1
Tags
Tag-key1
"name":"value"
Tag-key2
"name":"value"
fb-user-key2
user1-details2
Tags
Tag-key1
"name":"value"
Tag-Key1 & user-key's are generated by firebase with push(). firebase code to access the content is,
var fbref = firebase.database().ref("users");
fbref.child("Tags").on("child_added", function(e){
var Tagobj = e.val().name;
console.log(Tagobj);
});
This one is not returning anything. I am not able to access name:value pair in the above data structure.
`
adding modified code,
firebase.database().ref("users").on("child_added",function(eā€Œā€‹) { var Tagobj = e.val().Tags; });
Output of the above code is output data structure
How to access that name value pairs?? firebase keys are issue?
Not getting, where I am wrong. Appreciate your inputs.
Since Tags is a child property of each user, then you have to read it off of each user object.
If you want all Tags for all users, assuming Tags for each user is not updated after a user is created, you can do this:
tagsPerUserId = {};
firebase.datatabs().ref('users').on('child_added', function(snap) {
tagsPerUserId[snap.key] = snap.value().Tags;
// TODO: Notify view that tagerPerUserId is updated and needs to be re-rendered
console.log(`Tags for userId ${snap.key}: ${snap.value().Tags}`);
});
This way you will also get Tags of new users when they are created, but you will not get updates to Tags of existing users.

Accessing Other Entities Attributes in Dynamics CRM/365 Forms with javaScript

This function buttonBuzz() works inside the Forms of the Entities Account, Contacts and Leads. But not in the Opportunity form.
Mainly because there is no telephone1 attribute. There is however a Contact entity added with "Quick View" in a section with a telephonenumber inside.
I think it can be accessed with the telephone1 as well just not with Xrm.page
Any ideas how i can grab the attribute from inside the "quick view"?
I dont know if the "Quick view" window is a form of an iFrame. And if it is i have no clue how to access it with the Xrm.Page.getAttribute("telephone1").getValue();
function buttonBuzz(exObj) {
var phoneNumber;
// Here i store the "telephone1" Attribute from the current .page
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
if (phoneNumber != null) { **Sends phonenumber** } ...
Quick Views display data from a record selected in a lookup field, in this case a Contact. You can query data from related records using the OData endpoint.
You first need to get the Guid of the record selected:
var contactId = Xrm.Page.getAttribute("parentcontactid")[0].id || null;
You would then need to send a SDK.REST request, passing parameters for the Id of the record (contactId), entityName and the columns:
var entityName = "Contact";
var columns = "Address1_Telephone1, FirstName, LastName";
SDK.REST.retrieveRecord(contactId, entityName, columns, null, function(result) {
// Success, logic goes here.
var address1_Telephone1 = result.Address1_Telephone1;
}, function(e) {
console.error(e.message);
});
As well as your JavaScript file, you would need to include the SDK.REST.js file that is included in the MS CRM SDK download within your Opportunity form libraries.
You can pull that field up from the Contact into the Opportunity by creating a Calculated Field, setting it equal to parentcontactid.telephone1
Put the field on the form, and you'll be able to .getAttribute() it like any other Opportunity field (being Calculated, it updates itself whenever the source changes).

Firebase newest feed for following users

I'm working with Angularjs and Firebase. Right now I'm new at firebase for this I'm struggling to find solutions for my issues.
Imagine I'm sorting users like this
users:{
facebook:123456789:{
blog: [{
// List of blogs
}],
following: [{
// List of users auth.ids
}]
},
facebook:123456780:{
blog: [{
// List of blogs
}],
following: [{
// List of users auth.ids
}]
}
}
And getting logged in user blog object and iterating and pushing it to the array like this
var blogRef = new Firebase(FirebaseUrl + "/users/" + authData.uid + "/blog");
var userBlog = $firebaseArray(blogRef);
var userBlogDatas = []
blogRef.limitToLast(10).on("child_added", function(snapshot) {
var snap = snapshot.val();
userBlogDatas.push(snap);
});
So far everything working fine.
But how can i get latest blogposts from feeds from following users. Right now I have some idea which represents getting user blog datas and pushing them into array. I'm not sure is it right way or not...
I also read https://github.com/firebase/firefeed/blob/master/www/js/firefeed.js code but I could not get any information for myself.
Any ideas will be really helpfull.
Thank you
There's a couple of ways to do this if I am understanding the question correctly.
One way is that instead of storing the user_id, store the user id as a key and the blog id as the value like
users
facebook:123456789
blog
// List of blogs
following
user_id_0: blog_id_x
user_id_1: blog_id_y
Then you can add an observer to each blog in the following node. You can get the path from the key/value pair. In this case Facebook:123456789 is following:
/users/user_id_0/blog/blog_id_x
/users/user_id_1/blog/blog_id_y
Another option would be to create a child node within the following node that contains two values: the user_id and blog_id.
users
facebook:123456789
blog
// List of blogs
following
follow_id_0
userid: user_id_0
blog: blog_id_0
follow_id_1
userid: user_id_0
blog: blog_id_1
In this case, facebook:123456789 is following user_id_0's blog 0 and blog 1
Note: user_id_0 and user_id_1 are actually Facebook:abcdefg users id's

Accessing Firebase push() child

I'm slowly getting into Firebase but have what is probably a stupid question. If I am adding children to a reference using push(), how do I retrieve/delete them if I don't save the generated push ID?
For example, take this root:
var ref = https://myaccount.firebaseio.com/player
And if I write a new entry to /player:
var new_player= ref.push({
name:"User",
country:"United States"
})
Firebase generates a push ID for that:
https://myaccount.firebaseio.com/player/-JxgQCQsSLU0dQuwX0j-
which contains the information I pushed. Now lets say I want to retrieve or remove that player? Should I store the generated ID as a child of itself using .key() and .set()?:
//this will get -JxgQCQsSLU0dQuwX0j-
var _newPlayerKey = new_player.key();
//updates the record I just created
var update_player = ref.set({
name:"User",
country:"United States",
ref: _newPlayerKey
})
I don't see how else to access that object by it's generated ID... is there a better way to set this up?
Why are you doing that can't use the key() method, it should be adequate in almost all cases i.e.
playersRef.limit(10).on('child_added', function (snapshot) {
var player = "<p>"+ snapshot.val().name +" <button data-value='"+snapshot.key()+"'>Delete</button></p>";
$(player).appendTo($('#messagesDiv'));
});

Categories

Resources