создание системы лайков для пользователей, которым нравится сообщение/комментарий [vue3 firebase]

# #javascript #firebase #vue.js #google-cloud-firestore

Вопрос:

РЕДАКТИРОВАТЬ: решение этого вопроса, которое у меня было, находится в редактировании этого поста.

Я пытаюсь настроить подобную систему для публикации на веб-сайте, над которым я работаю. Я могу нажать кнопку «Нравится», и она добавляет приращение к счетчику «Нравится», и он отправляет идентификатор пользователя в likeId поле в нужном документе.

Проблема, с которой я сталкиваюсь, заключается в том, что если пользователь снова нажмет кнопку «Нравится», я хочу удалить их идентификатор из likeId массива и уменьшить количество голосов на единицу (по сути, в отличие от поста). У меня есть обе эти функции, работающие сами по себе, но я изо всех сил пытаюсь понять, как проверить, понравилось ли сообщение пользователю, и если да, то удалите их, если они снова нажмут кнопку «Нравится».

как бы то ни было, мне может нравиться сообщение неограниченное количество раз, или я могу не нравиться неограниченное количество раз, в зависимости от того, какую функцию я включаю вручную, но при попытке использовать оператор if, похоже, не работает .

post.likeID.userId возвращаемые значения не определены. post.likeId возвращает массив, в котором указаны идентификаторы пользователей, но я не могу понять, как сравнить их с текущим идентификатором пользователя, который покажет, понравился ли им уже пост или нет.

 const like = async (post) => {
  const userId = user.value.uid;

  if (post.likeId.userId !== userId) {
    await projectFirestore
      .collection("userPost")
      .doc(post.id)
      .update({
        likeId: firebase.firestore.FieldValue.arrayUnion({ userId }),
        likes: firebase.firestore.FieldValue.increment(1),
      });
  } else  {
    await projectFirestore
      .collection("userPost")
      .doc(post.id)
      .update({
        likeId: firebase.firestore.FieldValue.arrayRemove({ userId }),
        likes: firebase.firestore.FieldValue.increment(-1),
      });
  }
};
 

ПРАВКА: в конце концов я это понял. вот решение, которое я придумал, если кто-нибудь еще наткнется на это.

 const like = async (document) => {
      const userId = user.value.uid;

      if (document.likeId == null) {
        var likeIds = false; // if no one has liked this post yet, then set the likeId to false
      } else {
        var likeIds = document.likeId.indexOf(userId) != -1; //looks for the users Id in the array of user Ids who have liked
      } //the post. this array is called likeId. if the current users ID is
      //is not in the list  of likes then likeIds will return false

      if (likeIds == false) {
        //if it returns false because either the user hasnt liked it yet or no one has liked it yet.
        await projectFirestore
          .collection("userPost")
          .doc(document.id)
          .update({
            likeId: firebase.firestore.FieldValue.arrayUnion(userId), //then add the users ID to the likeId array
            likes: firebase.firestore.FieldValue.increment(1), //and increment the likes counter by 1 so we can display the number
          }); //of likes on the post easily
      } else {
        //else if the likeIds array returns true because the user Id is present meaning theyve liked the post already
        await projectFirestore
          .collection("userPost")
          .doc(document.id)
          .update({
            likeId: firebase.firestore.FieldValue.arrayRemove(userId), //then remove their user ID from the likeId array
            likes: firebase.firestore.FieldValue.increment(-1), //and decrease the likes counter by -1.
          });
        
      }
    };
 

here is a screen shot of what this looks like in the firebase document.
firebase document