javascript - firestore 查询中的条件 where 子句

标签 javascript firebase google-cloud-firestore

我已经从 firestore 获取了一些数据,但在我的查询中我想添加一个条件 where 子句。我正在为 api 使用 async-await,但不确定如何添加条件 where 子句。

这是我的功能

export async function getMyPosts (type) {
  await api
  var myPosts = []

  const posts = await api.firestore().collection('posts').where('status', '==', 'published')
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}

在我的主要功能中,我得到一个名为“类型”的参数。基于该参数的值,我想在上述查询中添加另一个 qhere 子句。例如,if type = 'nocomments',那么我想添加一个where子句。where('commentCount', '==', 0),否则如果 type = 'nocategories',则 where 子句将查询另一个属性,例如 .where('tags', '==', 'none')

我无法理解如何添加此条件 where 子句。

注意:在 firestore 中,您只需添加 where 子句即可添加多个条件,例如 - .where("state", "==", "CA").where("population", ">", 1000000 ) 等等。

最佳答案

仅在需要时将 where 子句添加到查询:

export async function getMyPosts (type) {
  await api
  var myPosts = []

  var query = api.firestore().collection('posts')
  if (your_condition_is_true) {  // you decide
    query = query.where('status', '==', 'published')
  }
  const questions = await query.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}

关于javascript - firestore 查询中的条件 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48689373/

相关文章:

javascript - 在 React 中迭代 JSON 对象中的多个数组

android - 确保首先在 Android 中调用 FirebaseApp.initializeApp(Context)

javascript - Firestore 权限被拒绝

android - 获取在 Firestore 中按文档 ID 降序排列的数据

javascript - 当我尝试一个接一个地调用我注册的协议(protocol)时,只有一个可以随机调用

javascript - Mongoose JS : How can I turn a Mongoose Collection into a standard Javascript array

javascript - 图像上的 Jquery UI Datepicker

firebase - 验证 Firestore 规则中的映射键

swift - 无法重新授权用户更改电子邮件或重置密码(Firebase .. Swift)

typescript - Firebase HTTPS 函数 - 在完成后台工作之前响应 200 状态代码