kom*_*hal 34 javascript firebase reactjs firebase-realtime-database
我在firebase中推送数据,但我想在我的数据库中存储唯一的id.有人可以告诉我,如何推送具有唯一ID的数据.
我是这样想的
writeUserData() {
var key= ref.push().key();
var newData={
id: key,
websiteName: this.webname.value,
username: this.username.value,
password : this.password.value,
websiteLink : this.weblink.value
}
firebase.database().ref().push(newData);
}
Run Code Online (Sandbox Code Playgroud)
错误是"ReferenceError:ref未定义"
iOS*_*eek 53
您可以使用key()任何ref对象的函数来获取密钥
push在Firebase的JavaScript SDK中有两种方法可以调用.
使用
push(newObject).这将生成一个新的推送ID并在具有该ID的位置写入数据.使用
push().这将生成一个新的推送ID并返回对具有该ID的位置的引用.这是一个纯粹的客户端操作.知道#2,您可以轻松获得一个新的推送ID客户端:
Run Code Online (Sandbox Code Playgroud)var newKey = ref.push().key();然后,您可以在多位置更新中使用此密钥.
如果在
push()没有参数的情况下调用Firebase 方法,则它是纯客户端操作.Run Code Online (Sandbox Code Playgroud)var newRef = ref.push(); // this does *not* call the server然后,您可以将
key()新参考添加到您的项目:Run Code Online (Sandbox Code Playgroud)var newItem = { name: 'anauleau' id: newRef.key() };并将项目写入新位置:
Run Code Online (Sandbox Code Playgroud)newRef.set(newItem);
在你的情况下:
writeUserData() {
var myRef = firebase.database().ref().push();
var key = myRef.key();
var newData={
id: key,
Website_Name: this.web_name.value,
Username: this.username.value,
Password : this.password.value,
website_link : this.web_link.value
}
myRef.push(newData);
}
Run Code Online (Sandbox Code Playgroud)
Ron*_*ton 27
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;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用 Promise 获取最后插入的项目 ID
let postRef = firebase.database().ref('/post');
postRef.push({ 'name': 'Test Value' })
.then(res => {
console.log(res.getKey()) // this will return you ID
})
.catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49507 次 |
| 最近记录: |