저는 양식에서 입력을 받아 카드에 표시하는 간단한 카드 카탈로그 프로젝트를 진행하고 있습니다.
각 카드에는 카드를 완전히 제거하거나 상자를 선택 / 선택 취소하는 옵션이 있습니다. 이렇게하려면 Firebase 실시간 데이터베이스의 개체에 액세스해야합니다.
각 개체는 a에 의해 .push()
생성되고 임의의 키 이름을 생성합니다.이 키 이름에 액세스하여 개체를 변경하거나 제거하고 싶습니다.
https://firebase.google.com/docs/database/web/read-and-write 에서 문서를 읽고 푸시하기 전에 키를 가져 오는 방법을 제공합니다. 이것은 제공된 예제에서 작동 update()
했지만 을 사용 했지만 내 push()
에서 시도했을 때 키가 일치하지 않았습니다.
또한 카드를 렌더링하는 별도의 함수에서 키를 사용해야하므로 전역 변수로 만들려고했고 undefined
.
다른 기능에서 사용하기 위해 키를 얻는 방법을 알려주시겠습니까?
감사!
newPostKey
여기 함수 내부에서 console.log 하면 데이터베이스의 내용과 일치하지만 외부에서 수행하면 undefined
.
var database = firebase.database();
let newPostKey;
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
console.log(newPostKey);
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);
이것은 newPostKey
내가 Firebase에서 보는 것과 일치하지 않는를 반환합니다 . 외부도 정의되지 않았습니다.
function writeNewPost(uid, username, picture, title, body) {
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
var newPostKey = firebase.database().ref().child('posts').push().key;
console.log(newPostKey);
return firebase.database().ref().child('posts').push(postData);
};
writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);
push
참조 를 호출 할 때마다 새 키가 생성됩니다. push()
두 번째 스 니펫에서 두 번 호출하므로 두 개의 키가 생성됩니다.
더 가능성이 높습니다.
var newPostKey;
function writeNewPost(uid, username, picture, title, body) {
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
newPostKey = firebase.database().ref().child('posts').push().key;
console.log(newPostKey);
return firebase.database().ref().child('posts').child(newPostKey).set(postData);
};
writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);
따라서 데이터 .child(newPostKey).set(postData)
대신 사용하여 새 키 대신 자식에 push(postData)
추가됩니다 newPostKey
.
DatabaseReference
푸시에 의해 반환 된 에서 키를 가져올 수도 있으므로 해당 코드를 다음과 같이 작성할 수도 있습니다.
function writeNewPost(uid, username, picture, title, body) {
return firebase.database().ref().child('posts').push({
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
});
};
let ref = writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(ref.key);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다