Node.js 从firestore中具有where条件的子集合的所有文档中删除数据
我想编写一个脚本,从status==expire的子集合的所有文档中删除数据。 我有集合名user_data,此集合包含许多文档所有文档都包含子集合名My_status,此My_status包含许多文档,每个文档都包含status,如果status==expire,则删除该数据 数据库结构如下Node.js 从firestore中具有where条件的子集合的所有文档中删除数据,node.js,database,firebase,google-cloud-firestore,Node.js,Database,Firebase,Google Cloud Firestore,我想编写一个脚本,从status==expire的子集合的所有文档中删除数据。 我有集合名user_data,此集合包含许多文档所有文档都包含子集合名My_status,此My_status包含许多文档,每个文档都包含status,如果status==expire,则删除该数据 数据库结构如下 collection - user_data document1 - Subcollection - My_status --document1- Status
collection - user_data
document1 - Subcollection - My_status --document1- Status expire
document2
document3
document2 - Subcollection - My_status --document1
document2--Status expire
document3
我已经试过了,但这不起作用,因为我无法将其与子集合联系起来
// First perform the query
db.collection('user_data').where('status','==',expire).get()
.then(function(querySnapshot) {
// Once we get the results, begin a batch
var batch = db.batch();
querySnapshot.forEach(function(doc) {
// For each doc, add a delete operation to the batch
batch.delete(doc.ref);
});
// Commit the batch
return.batch.commit();
}).then(function() {
// Delete completed!
// ...
});
更新:自2019年5月起,云Firestore现在支持。 您现在可以查询所有
My_status
子集合:
db.collectionGroup('My_status').where('','==', 'expire').get()
.then(function(querySnapshot) {
db.collection('user_data').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(userDocument) {
userDocument.ref.collection("My_status").where('status','==','expire').get()
.then(function(querySnapshot) {
...
原始答案
您现在尝试执行的操作称为“集合组查询”,目前不支持该查询。看
如果您试图从所有用户的My\u status
子集合中删除所有文档,则需要首先遍历所有用户,然后查询其每个子集合:
db.collectionGroup('My_status').where('','==', 'expire').get()
.then(function(querySnapshot) {
db.collection('user_data').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(userDocument) {
userDocument.ref.collection("My_status").where('status','==','expire').get()
.then(function(querySnapshot) {
...
或者,您可以将所有子集合中的数据存储在单个全局集合中,并将用户ID作为字段包含在其中。这样,您可以查询单个全局集合以删除所有过期文档