在向 Firebase 添加对象时设置您自己的密钥 - AngularFire [英] Setting Your Own Key When Adding an Object to Firebase - AngularFire
问题描述
我可以使用以下内容将对象添加到我的 Firebase 数据存储:
I can use the following to add an object to my Firebase data store:
var uniqueId = {
name: "a name",
location: "new york"
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
// do something on success
}, function(){
// do something if call fails
});
以上将向我的数据存储中添加一个对象,如果添加成功,则返回 Firebase 生成的 ID.我刚刚添加的对象保存在这个键下.
The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned. The object I just added is saved under this key.
当我添加到我的数据存储时,有没有办法让我指定密钥名称?
Is there a way for me to specify what the key name is when I add to my data store?
推荐答案
Firebase 中的一切都是一个 URL.
以下面的网址为例.
Everything in Firebase is a URL.
Take the following URL for example.
https://myapp.firebaseio.com/users/
假设我们要在此位置创建一个密钥为 1 的用户作为孩子.我们的 URL 看起来像这样.
Let's say we want to create a user with a key of 1 as a child at this location. Our URL would look like this.
https://myapp.firebaseio.com/users/1
要使用 AngularFire 创建用户,我们可以在 users 节点创建一个引用并调用 $child(1) 来创建对该位置的引用.
To create a user using AngularFire we can create a reference at the users node and call $child(1) to create a reference to that location.
var usersRef = new Firebase('https://myapp.firebaseio.com/users');
var userRef = new Firebase('https://myapp.firebaseio.com/user/1');
$scope.users = $firebase(usersRef);
// these are the same
$scope.userOne = $firebase(userRef);
$scope.userOne = $scope.users.$child(1);
然后我们可以使用 $set
来存储用户在那个位置的值.
Then we can use $set
to store the value of the user at that location.
var usersRef = new Firebase('https://myapp.firebaseio.com/users');
$scope.users = $firebase(usersRef);
$scope.users.$child(1).set({
first: 'Vincent',
last: 'Van Gough',
ears: 1
});
在你的情况下是:
var uniqueId = {
id: 1,
name: "a name",
location: "new york"
};
$scope.myItems.$child(uniqueId.id).$set(uniqueId);
请记住,使用 $set
会破坏该位置之前的所有数据.要非破坏性地更新值,请使用 $update
.
Remember that using $set
will destroy any previous data at that location. To non-destructively update the values use $update
.
这篇关于在向 Firebase 添加对象时设置您自己的密钥 - AngularFire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!