簡體   English   中英

在 Where 子句中使用變量的 Cloud Firestore 查詢不是工作節點

[英]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();
    }
  }

firestore 控制台文檔截圖 .collection .collection("posts").where("userId", "==", 1)的 firebase 控制台文檔截圖

VsCode 調試視圖

當您使用where()方法來構建Query時,作為第三個參數傳遞的值與聲明為第一個參數的字段具有相同類型,這一點非常重要。

如您的問題下的評論所示,經過一些調試后,您似乎將字符串作為字段值傳遞給數字類型的字段。 因此是空的QuerySnapshot

非常感謝 @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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM