首页 > 解决方案 > Firebase Firestore 是否允许在辅助查询中使用动态变量?

问题描述

我正在尝试进行一组相当基本的查询,其中第二个查询基于第一个查询的结果。

const fetchWatchlist = async (request: express.Request, response: express.Response) => {

  // fetch the watchlist according to the logged in user
  const watchlist = admin.firestore().collection('userdata').doc(request.userData.uid).collection('watchlist');

  const movieIds: string[] = [];
  const snapshot: admin.firestore.QuerySnapshot = await watchlist.get();
  snapshot.forEach((doc: admin.firestore.DocumentSnapshot) => {
    const watchlistItem: any = doc.data();
    movieIds.push(watchlistItem.movie_id);
  });

  // fetch movies matching watchlist
  const movies = admin.firestore().collection('movies').where(admin.firestore.FieldPath.documentId(), 'in', movieIds);
  const moviesSnapshot: admin.firestore.QuerySnapshot = await movies.get();

  const ret: Movie[] = [];
  moviesSnapshot.forEach((doc: admin.firestore.DocumentSnapshot) => {
    const movie: any = doc.data();
    ret.push({
      title: movie.title,
    });
  });

  return response.status(200).json({ data: ret });
}

第二个查询总是返回一个空快照。

问题可以进一步隔离:

const fetchWatchlist = async (request: express.Request, response: express.Response) => {

  // fetch the watchlist according to the logged in user
  const watchlist = admin.firestore().collection('userdata').doc(request.userData.uid).collection('watchlist');

  // hardcode data to check if document ID is present in
  const test = ['1', '2'];

  // fetch movies matching watchlist
  const movies = admin.firestore().collection('movies').where(admin.firestore.FieldPath.documentId(), 'in', test);
  const moviesSnapshot: admin.firestore.QuerySnapshot = await movies.get();
}

以下代码确实有效

where(admin.firestore.FieldPath.documentId(), 'in', ['1', '2']);

以下没有:

const test = ['1', '2'];
where(admin.firestore.FieldPath.documentId(), 'in', [...test]);

以下仅尊重最后一个硬编码的值

const test = ['1', '2'];

// this will return a match for '3', not nothing else from test;'
where(admin.firestore.FieldPath.documentId(), 'in', [...test, '3']);

这是在节点 8 的谷歌云功能(通过 firebase 功能)上运行的。

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读