[英]Cloud Firestore query with Variable in Where clause isn't working node
我正在嘗試將 firestore 集成到我的 nestjs 應用程序中。 當我嘗試使用不帶變量(硬編碼值)的where
子句從 firestore 檢索數據時,我能夠檢索數據,但是當我使用變量時,我只收到空數組。
這是我嘗試從 Firestore 檢索數據的代碼。
async getUserPosts(userId: number): Promise<PostsDocument[]> {
this.logger.log(`Getting posts for user with ID: ${userId}`);
const snapshot = await this.postsCollection
.where('userId', '==', userId)
.get();
const posts: PostsDocument[] = [];
snapshot.forEach((doc) => {
this.logger.debug(`Found post: ${doc.id}`);
posts.push(doc.data());
});
return posts;
}
當我用 1 替換 where 子句中的userId
變量時,我正在接收數據,但這不起作用。
[Nest] 1854 - 07/31/2022, 10:09:58 AM LOG [PostsService] Getting posts for user with ID: 1
我確實根據上面的日志驗證了是否收到了 userId。
這是我的 controller 代碼
@Get()
getUserPosts(@Query() query: { userId: number }) {
if (query.userId) {
return this.postsService.getUserPosts(query.userId);
} else {
return this.postsService.getPosts();
}
}
.collection
.collection("posts").where("userId", "==", 1)
的 firebase 控制台文檔截圖
非常感謝 @Renaud Tarnec 和 @Frank van Puffelen 提供的幫助。
問題:typescript 數字變量在while
子句中被視為字符串。
修復:將 userId 傳遞為Number(userID)
而不是 userId 已修復問題
const snapshot = await this.postsCollection
.where('userId', '==', Number(userId))
.get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.