我有一个Firestore users文档,它看起来如下所示:
{
currentCompanyId: "123",
displayName: "Mary Jane"
}以及一个类似于以下内容的Firestore websites文档:
{
companyId: "123",
homePageUrl: "https://www.google.com/"
}现在,我正在尝试使用VueUse useFirestore()包装器来显示websites文档。
为此,我在一个currentCompanyId查询约束中引用users文档的where属性,如下所示:
<template>
<div>
{{ websites?.[0] }}
</div>
</template>
<script setup lang="ts">
import { useAuth } from '@vueuse/firebase/useAuth';
import { useFirestore } from '@vueuse/firebase/useFirestore';
import { collection, doc, query, where } from 'firebase/firestore';
import { auth, db } from 'src/config/firebase';
import { User } from 'src/types';
import { computed } from 'vue';
const { user: authUser } = useAuth(auth);
const userDocRef = doc(db, `users/${authUser.value?.uid}`);
const user = useFirestore<User>(userDocRef);
const websiteQuery = computed(() =>
query(
collection(db, 'websites'),
where('companyId', '==', user.value?.currentCompanyId) // This produces an error
// where('companyId', '==', '123') // This works, but is not practical
)
);
const websites = useFirestore(websiteQuery);
</script>硬编码的companyId值的123工作。
但是,每当我在计算引用中使用user.value?.currentCompanyId时,它都会抛出一个错误,如下所示:
TypeError: in的右边应该是一个对象,获得null
发布于 2022-09-19 02:14:28
我想通了。
问题是user.value?.currentCompanyId最初是null。
以下是错误消息:
TypeError: in的右边应该是一个对象,获得null
它基本上是说Where查询约束的右侧应该是一个对象,但是它得到了null。
将查询包装在computed ref中,最终将在null更新时将其值更改为其他值。但一开始是null。这就是错误的原因。
为了克服这个问题,您可以在user中设置useFirestore的一些初始属性。因此,Where查询约束最初将使用该非空值。即使是空字符串也可以。您可以使用任何不是null的东西。
以下是完整的代码:
<template>
<div>
{{ websites?.[0] }}
</div>
</template>
<script setup lang="ts">
import { useAuth } from '@vueuse/firebase/useAuth';
import { useFirestore } from '@vueuse/firebase/useFirestore';
import { collection, doc, query, where } from 'firebase/firestore';
import { auth, db } from 'src/config/firebase';
import { User } from 'src/types';
import { computed } from 'vue';
const { user: authUser } = useAuth(auth);
const userDocRef = doc(db, `users/${authUser.value?.uid}`);
const user = useFirestore<User>(userDocRef, { currentCompanyId: '' }); // <-- See change here
const websiteQuery = computed(() =>
query(
collection(db, 'websites'),
where('companyId', '==', user.value?.currentCompanyId)
)
);
const websites = useFirestore(websiteQuery);
</script>发布于 2022-09-14 10:33:36
只有在定义了值时才尝试传递QueryConstraint,如下所示:
const websiteQuery = computed(() => {
const queryContraints: any = [];
const currentCompanyId = user.value?.currentCompanyId;
if (currentCompanyId) queryContraints.push(where("companyId", "==", currentCompanyId));
return query(
collection(db, 'websites'),
...queryContraints
)
});但是,如果不提供where()约束,这将返回所有文档,因此可能只在定义了查询时,即在加载auth状态之后才尝试运行查询。onAuthStateChanged()在这里可能很有用。
https://stackoverflow.com/questions/73715248
复制相似问题