Firestore:如何获取存在特定字段的所有文档
Firestore: How to get all documents where a specific field exist
我在 Firestore 中有一个集合,其中一些文档包含一个数组,但有些不包含。结构如下所示:
document1 = {
date: '2022-02-02',
name: 'x',
array: ['a'],
}
document2 = {
date: '2022-02-03',
name: 'y',
}
如何获取字段 array
存在的所有文档?所以在这个例子中只有 document1?
这些解决方案是否可行:
db.collection('employees').where(`array`, '!=', null).get();
db.collection('employees').where(`array`, '>=', []).get();
首先你应该尝试你的解决方案。
如果它们不起作用,您可以尝试遍历文档并检查 doc.data().array
是否存在
如何获取字段数组存在的所有文档?
当您向 Firestore 添加数据时,请确保为 array
字段提供空值,如下所示:
document1 = {
date: '2022-02-02',
name: 'x',
array: null,
}
这样,下面的查询就可以完美地工作了:
db.collection('employees').where(`array`, '!=', null).get();
如果它是一个正在进行的项目,并且 array
字段根本不存在,那么只需将现有文档更新为包含空值的 array
。这是可能的,因为 null is a supported data type in Firestore.
我在 Firestore 中有一个集合,其中一些文档包含一个数组,但有些不包含。结构如下所示:
document1 = {
date: '2022-02-02',
name: 'x',
array: ['a'],
}
document2 = {
date: '2022-02-03',
name: 'y',
}
如何获取字段 array
存在的所有文档?所以在这个例子中只有 document1?
这些解决方案是否可行:
db.collection('employees').where(`array`, '!=', null).get();
db.collection('employees').where(`array`, '>=', []).get();
首先你应该尝试你的解决方案。
如果它们不起作用,您可以尝试遍历文档并检查 doc.data().array
是否存在
如何获取字段数组存在的所有文档?
当您向 Firestore 添加数据时,请确保为 array
字段提供空值,如下所示:
document1 = {
date: '2022-02-02',
name: 'x',
array: null,
}
这样,下面的查询就可以完美地工作了:
db.collection('employees').where(`array`, '!=', null).get();
如果它是一个正在进行的项目,并且 array
字段根本不存在,那么只需将现有文档更新为包含空值的 array
。这是可能的,因为 null is a supported data type in Firestore.