简体   繁体   English

我可以在 angular firebase 集合的数据字段内插入、更新和删除数组吗?

[英]Can I insert, update and delete array inside a data field in angular firebase collection?

I have a collection users and inside that collection is a filed list in which I want to add list of favourite movies of a user.我有一个收藏用户,在该收藏中是一个归档列表,我想在其中添加用户最喜欢的电影列表。 User can add and remove movies as per wish.用户可以根据需要添加和删除电影。 I did manage to add list as array by using push().我确实设法通过使用 push() 将列表添加为数组。

My function我的 function

this.userData.list.push({
  movie_id: this.movie_detail.id,
});
let data: any = {
  id: this.userData.uid,
  password: this.userData.password,
  phone: this.userData.phone,
  role: this.userData.role,
  list: this.userData.list,
};
this.authService.updateUser(data);

Update function inside service:更新 function 内部服务:

updateUser(user) {
    const noteDocRef = doc(this.firestore, `users/${user.id}`);
    console.log('userDAta', noteDocRef);

    return updateDoc(noteDocRef, user);
}

这是结果

Right now same movie is being added multiple times.现在同一部电影被多次添加。 I want to prevent that.我想阻止这种情况。 I also want to delete the movie from list if user decides to click remove button.如果用户决定单击删除按钮,我还想从列表中删除电影。

To prevent duplicates in an array field, you can either remove duplicates in your application code, or leave it to the database by using the arrayUnion operator when adding an item to the list:为了防止数组字段中的重复项,您可以删除应用程序代码中的重复项,或者在将项目添加到列表时使用arrayUnion运算符将其留给数据库:

const noteDocRef = doc(this.firestore, `users/${user.id}`);

updateDoc(noteDocRef, {
  list: firebase.firestore.FieldValue.arrayUnion({ movie_id: this.movie_detail.id })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM