通过具有嵌套对象值的 where 子句查找记录
Find a records by where clause with nested object values
我想进行多项搜索,如果“sku”的 .where
未给出任何结果,请继续通过 additional_attributes.refKey
搜索值
关于如何根据嵌套对象值在 firestore 中查找记录的任何想法,例如:
const ref = db.collection('products')
let snapshot = await ref.where('sku', '==', req.query.id).get()
if (snapshot.empty) {
snapshot = await ref.where('additional_attributes', 'array-contains', req.query.id).get()
if (snapshot.empty) return res.json([])
}
const collection = []
snapshot.forEach(doc => {
collection.push({ id: doc.id, ...doc.data() })
})
res.json(collection)
我也这样试过:
snapshot = await ref.where('additional_attributes', 'array-contains', { refKey: req.query.id }).get()
但它也没有给我任何结果。知道我做错了什么吗?
您需要使用 dot notation
访问嵌套属性:
await ref.where('additional_attributes.refKey', '==', req.query.id)
// ^^^^^^
如果您正在查找数组中的元素,您可以使用相同的方法来使用其他运算符,例如 array-contains
。
我想进行多项搜索,如果“sku”的 .where
未给出任何结果,请继续通过 additional_attributes.refKey
关于如何根据嵌套对象值在 firestore 中查找记录的任何想法,例如:
const ref = db.collection('products')
let snapshot = await ref.where('sku', '==', req.query.id).get()
if (snapshot.empty) {
snapshot = await ref.where('additional_attributes', 'array-contains', req.query.id).get()
if (snapshot.empty) return res.json([])
}
const collection = []
snapshot.forEach(doc => {
collection.push({ id: doc.id, ...doc.data() })
})
res.json(collection)
我也这样试过:
snapshot = await ref.where('additional_attributes', 'array-contains', { refKey: req.query.id }).get()
但它也没有给我任何结果。知道我做错了什么吗?
您需要使用 dot notation
访问嵌套属性:
await ref.where('additional_attributes.refKey', '==', req.query.id)
// ^^^^^^
如果您正在查找数组中的元素,您可以使用相同的方法来使用其他运算符,例如 array-contains
。