Correct way to model a collection of items in Firebase

半世苍凉 提交于 2019-12-08 11:42:23

问题


In the docs I see a lot of examples using index values as a part of the key name for a particular item --- but I don't understand how this is a consistent way to model your data.

For example let's say I have a list of articles:

https://gigablox.firebaseio.com/articles/
article1
article2
article3

When I'm ready to add article4 I know I can use:

var length = Object.keys($scope.articles).length;

And using AngularFire 0.5.0 I can save it with:

var name = 'article' + length + 1;
$scope.articles[name] = $scope.article;
$scope.articles.$save(name);

But what happens if I:

$scope.articles.$remove('article2');

And add another record using the same approach? We're likely to create duplicate key names.

To add a little complexity, let's add a single relationship and say that each article has comments.

What is the correct way to model this data in a Firebase collection?


回答1:


Please use $add and let Firebase automatically generate chronologically ordered lists for you.

var ref = new Firebase("https://gigablox.firebaseio.com/articles/");
$scope.articles = $firebase(ref);

$scope.addArticle = function() {
  $scope.articles.$add($scope.article);
}

$scope.removeArticle = function(id) {
  $scope.articles.$remove(id);
}

Firebase automatically creates key names when you call $add. You can iterate over the key names using ng-repeat:

<div ng-repeat="(key, article) in articles">
  <div ng-model="article"><a ng-click="removeArticle(key)">Remove</a></div>
</div>



回答2:


EDIT: You should follow the suggestion from @Anant if you want an array-based collection.

However, for this specific scenario as outlined by @Dan Kanze, if you want to pull the key out of the URL (as would be done for a content management system, etc), you should generate your own keys unique to the content. For example, if you know that article names need to be unique, create a slug function that will:

  1. Lowercase the article name
  2. Replace spaces with underscores
  3. etc..

If the article name changes, you would not delete the old entry. Instead, create a new entry in Firebase and use the old key to point to the new location for 301 redirects, etc.



来源:https://stackoverflow.com/questions/20735728/correct-way-to-model-a-collection-of-items-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!