Javascript 通过Angular在firebase中创建具有自定义标题而不是ID的新项目
我正在通过Angular做一个后端,并使用Firebase作为DB 这一切都很好,我已经创建了一个控制器来创建新的罐-这是完美的工作 然而,当创建一个新帖子时,它会给firebase一个很长的随机IDJavascript 通过Angular在firebase中创建具有自定义标题而不是ID的新项目,javascript,angularjs,firebase,firebase-realtime-database,angularfire,Javascript,Angularjs,Firebase,Firebase Realtime Database,Angularfire,我正在通过Angular做一个后端,并使用Firebase作为DB 这一切都很好,我已经创建了一个控制器来创建新的罐-这是完美的工作 然而,当创建一个新帖子时,它会给firebase一个很长的随机ID .controller("VideosCtrl", function(firebase, $scope, $firebaseArray) { var ref = firebase.database().ref('posts') $scope.groups = $firebaseArray(r
.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创建新的pots,但是我不想使用一个随机的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
参考资料:谢谢您的时间boroboris,嗯,它似乎没有这样做,我在控制台上有一条消息,出现在提交时:TypeError:$scope.groups.child不是m.$scope.addgroup中$scope.groups.child($scope.newgroupTitle.set)行的函数({您知道为什么吗?我已经更新了答案。它似乎有点可疑。:)我想您需要$scope.groups.$ref().child($scope.newgroupTitle)。设置它才能工作。不过,我还没有正确测试它。