通过 Angular 在 firebase 中使用自定义标题而不是 ID 创建新项目

Create new item with custom title instead of ID in firebase via Angular

我正在通过 Angular 做后端并使用 Firebase 作为数据库。

一切都很好,我已经创建了一个控制器来创建新的花盆 - 效果很好。

但是,在创建新的 post 时,它会在 firebase 中提供一个非常长且随机的 ID。

.controller("VideosCtrl", function(firebase, $scope, $firebaseArray) {

 var ref = firebase.database().ref('posts')
 $scope.groups = $firebaseArray(ref);
$scope.addgroup = function() {
$scope.groups.$add({
  title: $scope.newgroupTitle,
  caption: $scope.newgroupCaption,
  creator: $scope.newgroupCreator,
  privacy: $scope.newgroupPrivacy,
  published: $scope.newgroupPublished,

 })

}

我正在使用 scope 来创建新的花盆,但我不想使用随机 ID 而使用来自

的标题
      title: $scope.newgroupTitle,

所以当前我创建 post 时我的数据库看起来像:

--mydomain
---- posts
------ RANDOM ID GENERATED
--------title
--------caption
--------creator
--------privacy
--------published
------ RANDOM ID GENERATED
--------title
--------caption
--------creator
--------privacy
--------published
----users

我想要:

--mydomain
---- posts
------ TITLE ( same as below)
--------title 
--------caption
--------creator
--------privacy
--------published
------ TITLE (same as below)
--------title
--------caption
--------creator
--------privacy
--------published
----users

任何推荐都会很棒!

感谢你们的帮助!

当您在 Firebase 中使用 $add 时,您会自动创建推送 ID。如果您想使用自定义 ID。相反,您应该使用 object.child(id).set(objectInfo);

我已经在下面修改了你的代码:

$scope.addgroup = function() {

  $scope.groups.$ref().child($scope.newgroupTitle).set({
    title: $scope.newgroupTitle,
    caption: $scope.newgroupCaption,
    creator: $scope.newgroupCreator,
    privacy: $scope.newgroupPrivacy,
    published: $scope.newgroupPublished
 });
}

这是纯 javascript 代码,但它应该可以工作,因为 angularfire 是在 javascript 库之上构建的。

这里要注意的一件事是,当您想使用自定义键在 Firebase 中存储对象时,最好使用 $firebaseObject 而不是 $firebaseArray

参考:angularfire issue on github.