cuốn sách gpt4 ai đã làm

javascript - 查询多个 Firestore 集合的同一字段

In lại Tác giả: Walker 123 更新时间:2023-11-28 16:48:01 25 4
mua khóa gpt4 Nike

我希望在多个集合中查找文档,其中的文档没有描述字段,我想避免循环,但想找到最有效的方法。此代码在一个集合中工作。

            firebase
.firestore()
.collection('creators') // ### Would need to loop for 4 others like this #####
.where('description', '==', '')
.get()
.then((snapshot) => {
if (snapshot.empty) {
console.log('No matching documents.')
return
}

snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data())
})
})
.catch((err) => {
console.log('Error getting documents', err)
})

câu trả lời hay nhất

Bạn có thể sử dụngPromise.all() 并行执行所有查询,如下所示:

   const db = firebase.firestore();

const q1 = db.collection('creators').where('description', '==', '...').get();
const q2 = db.collection('xyz').where('description', '==', '...').get();

return Promise.all([q1, q2])
.then(snapshotsArray => {

snapshotsArray.forEach(snap => {
snap.forEach(doc => {
console.log(doc.id, '=>', doc.data())
})
})

})

您可以将其简化如下:

   const collectionNames = ['creators', 'klmn', 'opqr', 'stuv']
const promises = collectionNames.map(x => db.collection(x).where('description', '==', '...').get());

Promise.all(promises)
.then(snapshotsArray => {

snapshotsArray.forEach(snap => {
snap.forEach(doc => {
console.log(doc.id, '=>', doc.data())
})
})

})

正如上面提到的文档中所解释的:

The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled

...

The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

Nhưng,

根据您问题中的这句话,有一点需要注意:“在多个集合中查找文档,其中包含没有描述字段的文档”。

您无法在 Firestore 中构建返回不带给定字段的文档的查询。原因(索引机制)这个官方video中已经很好的解释了.

另一方面,您可以查询具有空字段的文档:

db.collection('creators').where('description', '==', '').get();

或使用具有 vô giá trị 值的字段:

db.collection('creators').where('description', '==', null).get();

关于javascript - 查询多个 Firestore 集合的同一字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60300158/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress