最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - firebase $add() .push() .set() - Stack Overflow

programmeradmin5浏览0评论

I am using firebase, and angularfire. there are so many ways to do CRUD with the Firebase Api actually, I still don't get what is specific difference for using

  • $add with $firebaseArray
  • .push() method
  • .set() method

I think they are technically same, I prefer to use .set method() without knowing the exact reason, why I'd using that. is there any specific reason to not use it? what is exactly $firebaseArray did? if we could just declare basic reference variable.

in this case:

var usersRef = Ref.child('users');

  $scope.createUser = function() {
    $scope.userRef.child($id).set({
       name: name
           });
      };

or

$scope.data = $firebaseArray(Ref.child('users'));

$scope.createUser = function() {
  $scope.data.child($id).$add({
    name: name
  });
 };

thank you.

I am using firebase, and angularfire. there are so many ways to do CRUD with the Firebase Api actually, I still don't get what is specific difference for using

  • $add with $firebaseArray
  • .push() method
  • .set() method

I think they are technically same, I prefer to use .set method() without knowing the exact reason, why I'd using that. is there any specific reason to not use it? what is exactly $firebaseArray did? if we could just declare basic reference variable.

in this case:

var usersRef = Ref.child('users');

  $scope.createUser = function() {
    $scope.userRef.child($id).set({
       name: name
           });
      };

or

$scope.data = $firebaseArray(Ref.child('users'));

$scope.createUser = function() {
  $scope.data.child($id).$add({
    name: name
  });
 };

thank you.

Share Improve this question edited Apr 12, 2016 at 11:47 gema asked Apr 12, 2016 at 11:39 gemagema 5241 gold badge7 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

If I have the following data tree in Firebase:

{
  users:
   {
      key: { name:"bob" }
   }
}

When I do an $add, I will create a new item in the tree

$scope.data.child('users').$add({
    name: name
  });

Since $add uses the Push method in Firebase, new random Key will be used when pushing data to the child.

{
  users:
   {[
      key: { name:"bob" },
      key2: { name:"name" }
   ]}
}

If I do a set on the same Users object, I will overwrite the data that is already there. So, in your example, without specifying a key, you will overwrite the entire user object.

$scope.userRef.child('users').set({
       name: name
           });
      };

This will result with this data

{
  users:
   {
      name: "name"
   }
}

This happens because any null values you pass to the Set method will delete any data that was originally there.

Passing null to set() will remove the data at the specified location. https://www.firebase./docs/web/api/firebase/set.html

发布评论

评论列表(0)

  1. 暂无评论