我在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);
}错误是"ReferenceError: ref未定义“
发布于 2016-08-04 13:24:33
您可以通过使用任何ref对象的函数key()来获取密钥。
在Firebase的
pushSDK中有两种调用JavaScript的方法。
push(newObject)。这将生成一个新的push id,并使用该id在该位置写入数据。push()。这将生成一个新的push id,并使用该id返回对位置的引用。这是一个纯粹的客户端操作。了解#2之后,您可以很容易地获得一个新的push id客户端:
var newKey = ref.push().key();
然后,您可以在多位置更新中使用此键。
https://stackoverflow.com/a/36774761/2305342
如果不带参数地调用Firebase
push()方法,则它是纯客户端操作。 var newRef = ref.push();//此不调用服务器 然后,可以将新引用的key()添加到项目中: var newItem ={ name:'anauleau‘id: newRef.key() }; 并将项目写入新位置: newRef.set(newItem);
https://stackoverflow.com/a/34437786/2305342
就你而言:
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);
}发布于 2016-08-04 20:21:53
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);
}发布于 2017-12-13 07:24:39
您可以使用这样的承诺获得最后插入的项目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));https://stackoverflow.com/questions/38768576
复制相似问题