Firebase를 사용하여 이름 속성별로 사용자 확보
특정 사용자 계정에서 데이터를 가져 오거나 설정할 수있는 애플리케이션을 만들려고하는데 Firebase의 유혹을 받았습니다.
내가 겪고있는 문제는 내 구조가 다음과 같은 경우 특정 사용자 데이터를 타겟팅하는 방법을 모른다는 것입니다.
online-b-cards
- users
- InnROTBVv6FznK81k3m
- email: "hello@hello"
- main: "Hello world this is a text"
- name: "Alex"
- phone: 12912912
주위를 둘러 보았으며 ID로 임의의 해시가 주어지면 개별 데이터에 액세스하는 방법에 대해서는 실제로 아무것도 찾을 수 없습니다.
이름을 기준으로 개별 사용자 정보를 가져 오려면 어떻게해야합니까? 더 좋은 방법이 있다면 알려주세요!
이전에는 Firebase에서 자체 속성 을 생성 하거나 특정 위치에서 모든 데이터를 다운로드하여 일부 하위 속성 (예 :의 모든 사용자)과 일치하는 요소를 찾고 검색해야했습니다 name === "Alex"
.
2014 년 10 월 Firebase는이 orderByChild()
방법을 통해 새로운 쿼리 기능을 출시하여 이러한 유형의 쿼리를 빠르고 효율적으로 수행 할 수 있습니다. 아래의 업데이트 된 답변을 참조하십시오.
Firebase에 데이터를 쓸 때 다양한 사용 사례를 반영하는 몇 가지 옵션이 있습니다. Firebase는 기본적으로 트리 구조의 NoSQL 데이터 저장소이며 데이터 목록 관리를위한 몇 가지 간단한 기본 요소를 제공합니다.
고유하고 알려진 키를 사용하여 Firebase에 씁니다 .
ref.child('users').child('123').set({ "first_name": "rob", "age": 28 })
작성된 시간별로 자동 정렬되는 자동 생성 키가있는 목록에 추가 :
ref.child('users').push({ "first_name": "rob", "age": 28 })
고유하고 알려진 경로로 데이터의 변경 사항을 청취하십시오 .
ref.child('users').child('123').on('value', function(snapshot) { ... })
키 또는 속성 값 으로 목록의 데이터를 필터링 하거나 주문하십시오 .
// Get the last 10 users, ordered by key ref.child('users').orderByKey().limitToLast(10).on('child_added', ...) // Get all users whose age is >= 25 ref.child('users').orderByChild('age').startAt(25).on('child_added', ...)
를 추가 orderByChild()
하면 더 이상 하위 속성에 대한 쿼리를위한 고유 인덱스를 만들 필요가 없습니다! 예를 들어, 이름이 "Alex"인 모든 사용자를 검색하려면 다음을 수행하십시오.
ref.child('users').orderByChild('name').equalTo('Alex').on('child_added', ...)
Firebase 엔지니어입니다. Firebase에 데이터를 쓸 때 다양한 애플리케이션 사용 사례를 반영하는 몇 가지 옵션이 있습니다. Firebase는 NoSQL 데이터 저장소이므로 데이터 항목을 고유 한 키로 저장해야 해당 항목에 직접 액세스하거나 특정 위치에서 모든 데이터를로드하고 각 항목을 반복하여 찾고있는 노드를 찾을 수 있습니다. . 자세한 내용은 데이터 쓰기 및 목록 관리 를 참조하십시오.
Firebase에 데이터를 쓸 때 set
고유하고 정의 된 경로 (예 :)를 사용하는 데이터 a/b/c
또는 push
목록에 데이터를 입력하면 고유 한 ID (예 :)가 생성 a/b/<unique-id>
되고 시간별로 해당 목록의 항목을 정렬하고 쿼리 할 수 있습니다 . 위에서 본 고유 ID는 push
의 목록에 항목을 추가하기 위해 호출 하여 생성됩니다 online-b-cards/users
.
push
여기를 사용하는 대신을 사용 set
하고 사용자의 이메일 주소와 같은 고유 키를 사용하여 각 사용자의 데이터를 저장하는 것이 좋습니다 . 그런 다음 online-b-cards/users/<email>
Firebase JS SDK 를 통해 직접 탐색하여 사용자의 데이터에 액세스 할 수 있습니다 . 예를 들면 다음과 같습니다.
function escapeEmailAddress(email) {
if (!email) return false
// Replace '.' (not allowed in a Firebase key) with ',' (not allowed in an email address)
email = email.toLowerCase();
email = email.replace(/\./g, ',');
return email;
}
var usersRef = new Firebase('https://online-b-cards.firebaseio.com/users');
var myUser = usersRef.child(escapeEmailAddress('hello@hello.com'))
myUser.set({ email: 'hello@hello.com', name: 'Alex', phone: 12912912 });
Note that since Firebase does not permit certain characters in references (see Creating References), we remove the .
and replace it with a ,
in the code above.
You can grab the details by the following code.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users");
myRef.orderByChild("name").equalTo("Alex").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "PARENT: "+ childDataSnapshot.getKey());
Log.d(TAG,""+ childDataSnapshot.child("name").getValue());
}
I think the best approach is to define the ids of the users based o the auth object provided by the Firebase. When I create my users, I do:
FirebaseRef.child('users').child(id).set(userData);
This id comes from:
var ref = new Firebase(FIREBASE);
var auth = $firebaseAuth(ref);
auth.$authWithOAuthPopup("facebook", {scope: permissions}).then(function(authData) {
var userData = {}; //something that also comes from authData
Auth.register(authData.uid, userData);
}, function(error) {
alert(error);
});
The Firebase auth services will always ensure a unique id among all their providers to be set at uid. This way always you will have the auth.uid and can easily access the desired user to update it, like:
FirebaseRef.child('users').child(id).child('name').set('Jon Snow');
This was a paraphrasing of a post that helped me when trying to access the auto-generated unique id. Access Firebase unique ids within ng-repeat using angularFire implicit sync
Thanks, bennlich (source):
Firebase behaves like a normal javascript object. Perhaps the example below can get you on the right track.
<div ng-repeat="(name, user) in users">
<a href="" ng-href="#/{{name}}">{{user.main}}</a>
</div>
Edit: Not 100% sure of your desired outcome, but here's a bit more that might spark an 'aha' moment. Click on the key that you are trying to access right in your Firebase dashboard. From there you can use something like:
var ref = new Firebase("https://online-b-cards.firebaseio.com/users/<userId>/name);
ref.once('value', function(snapshot) {
$scope.variable= snapshot.val();
});
This is how to access the auto generated unique keys in Firebase: data structure: - OnlineBcards - UniqueKey
database.ref().on("value", function(snapshot) {
// storing the snapshot.val() in a variable for convenience
var sv = snapshot.val();
console.log("sv " + sv); //returns [obj obj]
// Getting an array of each key in the snapshot object
var svArr = Object.keys(sv);
console.log("svArr " + svArr); // [key1, key2, ..., keyn]
// Console.log name of first key
console.log(svArr[0].name);
}, function(errorObject) {
console.log("Errors handled: " + errorObject.code);
});
The simplest way is to stop using the .push(){}
function which will generate that random key. But instead use the .update(){}
function where you may specify the name of the child instead of having the random key.
Retrieving data:
In your database, you are using a random id that is generated using the push()
, therefore if you want to retrieve the data then do the following:
Using Firebase in Android App:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String name=datas.child("name").getValue().toString();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Using Firebase in Javascript:
firebase.database().ref().child("users").on('value', function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var name=childSnapshot.val().name;
});
});
Here you have the snapshot(location of the data) at users
then you loop inside all the random ids and retrieve the names.
Retrieving data for a Specific User:
Now if you want to retrieve information for a specific user only, then you need to add a query:
Using Firebase in Android App:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("users");
Query queries=ref.orderByChild("name").equalTo("Alex");
queries.addListenerForSingleValueEvent(new ValueEventListener() {...}
Using Firebase with Javascript
firebase.database().ref().child("users").orderByChild("name").equalTo("Alex").on('value', function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var name=childSnapshot.val().name;
});
});
Using orderByChild("name").equalTo("Alex")
is like saying where name="Alex"
so it will retrieve the data related to Alex.
Best Way:
가장 좋은 방법은 Firebase 인증을 사용하여 각 사용자에 대해 고유 한 ID를 생성하고 임의의 ID 대신에이를 사용하는 것입니다. push()
이렇게하면 ID가 있으므로 쉽게 액세스 할 수 있으므로 모든 사용자를 반복 할 필요가 없습니다.
먼저 사용자가 로그인 한 후 고유 ID를 검색하고 리스너를 연결하여 해당 사용자의 다른 데이터를 검색 할 수 있습니다.
Android에서 Firebase 사용하기 :
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
String uid = FirebaseAuthentication.getInstance().getCurrentUser().getUid();
ref.child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("name").getValue().toString();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Javascript와 함께 Firebase 사용 :
var user = firebase.auth().currentUser;
var uid=user.uid;
firebase.database().ref().child("users").child(uid).on('value', function (snapshot) {
var name=snapshot.val().name;
});
인증 된 사용자에 따라 고유 한 ID를 ur 데이터베이스에 추가하는 가장 간단하고 효과적인 방법은 다음과 같습니다.
private FirebaseAuth auth;
String UId=auth.getCurrentUser().getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");
User user = new User(name,email,phone,address,dob,bloodgroup);
myRef.child(UId).setValue(user);
UId는 인증 된 특정 이메일 / 사용자를위한 고유 ID입니다.
참고 URL : https://stackoverflow.com/questions/14963776/get-users-by-name-property-using-firebase
'Programming' 카테고리의 다른 글
GitHub-작성자 별 커밋 목록 (0) | 2020.07.06 |
---|---|
PHP ORM : 교리와 프로 펠 (0) | 2020.07.06 |
가동 중지 시간없이 ASP.NET 응용 프로그램을 배포하는 방법 (0) | 2020.07.06 |
Mercurial에서 닫힌 지점을 다시 열 수 있습니까? (0) | 2020.07.06 |
얕은 자식 서브 모듈을 만드는 방법? (0) | 2020.07.06 |