【问题标题】:How do I update an object in Firebase specific property?如何更新 Firebase 特定属性中的对象?
【发布时间】:2018-08-29 22:49:40
【问题描述】:
我正在尝试使用 Angular 4 和 AngularFire2 更新 Firebase 中的用户。在保存到 firebase 数据库的用户对象中,我想将另一个对象插入到数组属性中。在我的服务中,我正在尝试执行此功能(我已经拥有钥匙等所有内容)
generateUserCharacterList(){
this.genCharList = new CharacterList(x, y, z)
this.UserListOfCharacters.push(this.genCharList)
//Other code...
}
这不起作用
【问题讨论】:
标签:
javascript
angular
firebase
angularfire2
【解决方案1】:
Update specific fields 文档表明使用了.update 方法。
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
【解决方案2】:
我正在考虑您使用的是 firebase 实时数据库,而不是 firestore。
您应该在变量中获取数组的值,更改该值,然后使用该新值调用对象 ref 的更新方法。这是解释的代码示例:
let userRef = db.object('users/aad1asd123-123asd');
let user = userRef.valueChanges();
let listOfChars = user.listOfChars;
listOfChars.push('a');
listOfChars.push('b');
listOfChars.push('c');
listOfChars.push('d');
userRef.update({listOfChars: listOfChars});