我正在尝试进行聊天,在每条消息的顶部显示用户在发送每条消息时添加的每个文档的顶部的名称,但如果没有文档的其余部分,我无法获取单个字段。
<script>
import { projectFirestore } from '../Firebase/Config'
import { firebaseAuth } from "../Firebase/firebase";
import getChat from "../Composables/getChat";
import { ref } from 'vue'
import { timestamp } from '../Firebase/Config'
import getPSubscribed from '../Composables/getPremium'
export default {
setup(){
const { PSubscribed, load2 } = getPSubscribed(firebaseAuth.currentUser.uid);
load2()
const { Chat, error, load } = getChat();
load();
const name = PSubscribed.Username
const message = ref('')
const Activate = ref(false)
const handleSubmit = async () => {
const NewChat = {
name: name.value,
message: message.value,
createdAt: timestamp(),
}
const res = await projectFirestore.collection('Subscribed').doc(firebaseAuth.currentUser.uid).collection('messages').add(NewChat)
}
return { handleSubmit, Activate, message, Chat, load, load2, PSubscribed, name }
}
}
</script>
<template>
<div class="chat-window">
<div class="grid grid-cols-1 justify-items-center gap-y-2">
<div v-for =" doc in Chat" :key="doc.id" class="rounded-xl bg-red-100 w-max md:w-1/3 lg:w1/3 xl:w-1/5 2xl:w-1/5">
<p class="font-bold">{{ doc.name }}</p><br>
<p class="text-left mx-4">{{ doc.message }}</p>
<p class="created-at">{{ doc.createdAt.toDate() }}</p>
</div><br><br>
</div>
<form @submit.prevent="handleSubmit">
<textarea class="w-max md:w-2/3 lg:w-2/3 xl:w-2/5 2xl:w-3/5 p-10 rounded-xl outline-none"
placeholder="Type a message and hit enter to send..."
v-model="message"
></textarea><br>
<button @click="Loading = true" class="bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-800 text-red-700 hover:text-neutral-400 hover:scale-105 text-xl w-64 p-4 rounded-xl shadow cursor-pointer inline-block m-10 transition ease-in-out duration-300 drop-shadow-2xl"
>{{ Loading ? "Sending..." : "Send" }}</button>
<div v-if="error" class="error">{{ error }}</div>
</form>
</div>
</template>
上面是我要显示消息的页面,下面是我获取 PSubscribed 的位置以及属于该用户的文档。
import { projectFirestore } from "../Firebase/Config";
import { ref } from "vue"
const getPSubscribed = (id) => {
const PSubscribed = ref(null)
const error = ref(null)
const load2 = async () => {
try{
let res = await projectFirestore.collection('Subscribed').doc(id).get()
if(!res.exists) {
throw Error('That Profile no longer exists')
}
PSubscribed.value = {...res.data(), id: res.id}
// console.log(PSubscribed.value)
}
catch (err){
error.value = err.message
console.log(error.value)
}
}
return { PSubscribed, error, load2}
}
export default getPSubscribed
有谁知道如何获取 PSubscribed 的用户名字段并将其添加到名称值下?
如何从 Firestore 文档中仅获取一个单一字段?
使用客户端 SDK 无法仅读取文档中的一个字段。它要么是整个文档,要么什么都没有。然而,有两种方法可以解决这个问题。您可以复制文档,这意味着您将拥有一个包含所有字段的文档和另一个仅包含单个字段的文档。或者,您可以使用 Firestore Node.js 客户端或 Firebase Admin SDK,然后您可以使用 select() 仅选择 您需要的字段。