【发布时间】:2021-10-16 09:46:52
【问题描述】:
这是用户内部的外观>{uid}:
movies_collections = {
Action: ["tt0088247", "tt0103064", "...", "..."],
Comedy: ["...", "...]
.
.
.
}
所以...“movies_collections”对象/地图有键,这些键是用户设置的电影集合的自定义名称,每个键都与包含电影 imdbID 的字符串数组配对。
我正在努力做的事情:
在我的网站上,当用户单击电影旁边的加号时,它会向他们显示他们拥有的电影收藏的名称(动作、喜剧等)。我想要实现的下一步是当用户单击movies_collections 键时,我想将他们当前所在的电影添加到键的数组中
目前,当用户点击加号按钮时,它会向他们显示他们可用的电影收藏:
下面是代码:
// Each "plus" button attached to a movie has the id of the movie's imdbID, which starts with a "t"
if (e.target.id[0] === "t") {
// Get the movie's imdbID
const movieID = e.target.id;
// Get the available movie collections
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.get()
.then((doc) => {
// Get a reference to the "movies_collections" collection, which is an object
const moviesCollection = doc.data().movies_collections
// Show user's movies collections
Object.keys(moviesCollection).forEach(collection => {
// Add each key to the innerHTML of the "Add to Collection" button's parent element
document.getElementById(movieID).parentElement.parentElement.parentElement.innerHTML +=
`
<br>
<a class="collection-button" id="${collection} ${movieID}" href="#">
${collection}
</a>
`
})
})
}
然后,当用户点击 movies_collections 键(比如 Action)时,我有以下代码:
// When a movie collection is clicked, add the movie to the collection
if (e.target.className === "collection-button") {
// 1st ID of the collection button = name of the "movies_collections" key in Firestore
const collectionName = e.target.id.split(" ")[0].toString();
// 2nd ID of the collection button = the movie's imdbID
const movieIdName = e.target.id.split(" ")[1];
// Get the movies_collections key with that id inside Firestore, and insert the value of the second id into that key as a value. Basically, add the new movie into the array of the collection the user wants to add it to.
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.get()
.then((doc) => {
// TODO: append the movies_collections key with the new movie's imdbID
})
}
这就是我卡住的地方。我不知道如何将电影的 imdbID 添加/推送到相应集合的数组中。任何帮助表示赞赏。
【问题讨论】:
-
您可以使用 arrayUnion 将新值推送到数组中,如下所示:stackoverflow.com/questions/48231957/… 和 SDK 文档:firebase.google.com/docs/reference/js/…
标签: javascript html firebase google-cloud-firestore