logo
down
shadow

Return all docs when all docs are deleted in a collection in Firestore


Return all docs when all docs are deleted in a collection in Firestore

By : Sam
Date : October 18 2020, 01:08 AM
wish help you to fix your issue First of all, avoid the Promise constructor antipattern:
code :
function deleteCollection(db, collectionRef, batchSize) {
  var query = collectionRef.limit(batchSize);
  return deleteQueryBatch(db, query, batchSize);
}

function deleteQueryBatch(db, query, batchSize) {
  return query.get().then(snapshot => {
    if (snapshot.size == 0) return 0;
    var batch = db.batch();
    snapshot.docs.forEach(doc => { batch.delete(doc.ref); });
    return batch.commit().then(() => snapshot.size);
  }).then(function(numDeleted) {
    if (numDeleted >= batchSize) {
      // I don't think process.nextTick is really necessary
      return deleteQueryBatch(db, query, batchSize);
    }
  });
}
async function deleteQueryBatch(db, query, batchSize) {
  const snapshot = await query.get();
  if (snapshot.size > 0) {
    let batch = db.batch();
    snapshot.docs.forEach(doc => { batch.delete(doc.ref); });
    await batch.commit();
  }
  if (snapshot.size >= batchSize) {
    // await new Promise(resolve => process.nextTick(resolve));
    return deleteQueryBatch(db, query, batchSize);
  }
}
function deleteCollection(db, collectionRef, batchSize) {
  return deleteQueryBatch(db, collectionRef.limit(batchSize), batchSize, []);
}
async function deleteQueryBatch(db, query, batchSize, results) {
  const snapshot = await query.get();
  if (snapshot.size > 0) {
    let batch = db.batch();
    snapshot.docs.forEach(doc => {
      results.push(doc);
      batch.delete(doc.ref);
    });
    await batch.commit();
  }
  if (snapshot.size >= batchSize) {
    return deleteQueryBatch(db, query, batchSize, results);
  } else {
    return results;
  }
}


Share : facebook icon twitter icon
Firestore get all docs and subcollections of root collection

Firestore get all docs and subcollections of root collection


By : Anuj Dixit
Date : March 29 2020, 07:55 AM
Hope that helps As we know querying in Cloud Firestore is shallow by default. This type of query isn't supported, although it is something Google may consider in the future.
Deleting docs in a collection using Angular in Firestore

Deleting docs in a collection using Angular in Firestore


By : Federico Sabatino
Date : March 29 2020, 07:55 AM
this will help I figured that I was missing the type on the variable I was looking at, I did however not know how to declare the type of that variable in a arrow function as trying to include external variables into the function did not work for me.
I fixed my error by adding the type as seen in my code here. Now the code works just like before AND it does not give me a compiler error.
code :
deleteDoc() {
    this.db.collection(`tests/${this.testID}/questions`,
        ref => ref.orderBy('order')).valueChanges().subscribe(questions => {
        questions.map((question: Question) => {
            this.db.doc(`tests/${this.testID}/questions/${question.id}`).delete()
                .catch(error => {console.log(error); })
                .then(() => console.log(`Deleting question (${question.id}) in (${this.testID})`));
        });
    });
    this.testDoc.delete().catch(error => console.log(error)).then(() => console.log(`${this.testID} has been deleted.`));
}
$lookup within the same collection is nesting docs instead of returning all docs

$lookup within the same collection is nesting docs instead of returning all docs


By : Chrissy Collins
Date : March 29 2020, 07:55 AM
should help you out That is because you create an empty array __department in the document that didn't find a match in the $lookup. This is how your orphan document looks like:
code :
{
    "_id" : ObjectId("5a1982646462db032d58c3f9"),
    "department" : false,
    "desc" : "Operations Department",
    "type" : "main",
    "__department" : []
}
{
        $project: {
            _id: 1,
            department: 1,
            name: 1,
            type: 1,
            __department: {
                $cond: [{
                        $eq: ["$__department", []]
                    },
                    [{
                        _id: 0,
                        department: "None", 
                        desc: "None",
                        type: "None"
                    }], '$__department'
                ]
            }
        }
    }
[{
        '$lookup': {
            'as': '__department',
            'foreignField': '_id',
            'from': 'depart',
            'localField': 'department'
        }
    },
    {
        '$project': {
            _id: 1,
            department: 1,
            name: 1,
            type: 1,
            __department: {
                $cond: [{
                        $eq: ["$__department", []]
                    },
                    [{
                        _id: 0,
                        department: "None", 
                        desc: "None",
                        type: "None"
                    }], '$__department'
                ]
            }
        }
    },
    {'$unwind': "$__department"},
    {'$group': {'__department': {'$first': '$__department'},
             '_id': '$_id',
             'department': {'$first': '$department'},
             'name': {'$first': '$name'},
             'type': {'$first': '$type'}}}]
Does value of docs.count in elasticsearch also include value of docs.deleted?

Does value of docs.count in elasticsearch also include value of docs.deleted?


By : kevinrhurst
Date : March 29 2020, 07:55 AM
help you fix your problem The counts you see in the _cat/indices API response are counts at the Lucene level, so docs.count also includes hidden nested documents.
docs.deleted are indeed documents marked as deleted but not yet expunged.
Get sum of values from unique docs in collection of duplicate docs in MongoDB

Get sum of values from unique docs in collection of duplicate docs in MongoDB


By : user3420633
Date : March 29 2020, 07:55 AM
it helps some times You need to sum inside of the $group _id field, and then use the replaceRoot to achieve the the result you wanted.
code :
MaterialsTrack.aggregate([
  {
    $match: {
      $and: [
        {
          product_name: "Bottle"
        },
        {
          account_name: "mrfsahas1234"
        },
        {
          action_type: "purchase"
        },
        {
          uid: "2019-11-20T17:39:17.405Z"
        }
      ]
    }
  },
  {
    $group: {
      _id: {
        sellingId: "$sellingId",
        PurchaseQuantity: {
          $sum: "$product_quantity"
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        _id: "$_id.sellingId",
        PurchaseQuantity: "$_id.PurchaseQuantity"
      }
    }
  }
]);
[
  {
    "PurchaseQuantity": 50,
    "_id": "320a9a2f814a45e01eb98344c9af708fa2864d81587e5914"
  }
]
Related Posts Related Posts :
  • Use html link to open javascript modal
  • Check if text input is not empty
  • How do I validate start time and end time using select
  • Form submit is not prevented when trying to integrate VueJS with SemanticUI
  • Should i install node and npm if i am not a node programme but i want to use bower?
  • ng-view does not get the data from href?
  • THREE.js - Graphical Glitch with an imported model
  • ViewModel current state to JSON
  • How to stop multiple row highlighting
  • Custom input element in native form
  • Angular service unable to execute function
  • Enable/disable input field depending on array length in Angular 1.5
  • Angular Load Json Error
  • how is dart compiled into javascript?
  • How to create dynamic radio button using javascript
  • Nodejs/Express - Error: Can't set headers after they are sent
  • javascript remove all elements :Uncaught SyntaxError: Unexpected identifier
  • onchange event of text box not working if i change text value dynamically
  • Determine the position of the view port scroll bar
  • Uploading file on site from DropBox
  • How to change the legends from vertical view to horizontal view?
  • Recursive function to create a tree
  • How to apply my class from css to checkbox?
  • If statement on every case within switch
  • checking JSON Data contains media or not..?
  • Binding a list with deviders to the DOM AngularJS
  • Extra blank space is including in dynamic dropdown in angularjs
  • How do I only update one value of my reducer in Redux?
  • Display embedded PDF in Internet Explorer 11 from binary string or base64
  • Convert String to nested array of characters
  • Angular 2 HTTP get handling 404 error
  • Single page with multiple states controlled by URL
  • call prototype method inside callback function of prototype method
  • How To Put Values Dynamically
  • I have custom google map multiple markers.when i am using reverse geolocation for multiple marker
  • Use casperjs to get all links from a page
  • Modify url path without redirection
  • Jquery "hasClass" not working
  • how to change col-span when a data is added to html table cell
  • Stopping links inside of a table from marking table row as selected
  • Angular 1.4 ng-if and ng-repeat to menu
  • Sending a list of checkboxes via Ajax to Django
  • ng-model not updated from controller to view
  • Node command is not working in cmd after installing node on windows?
  • Delay part of the funcion execution JavaScript and exit function
  • JS addition game: how do I display 4 possible answers, 3 of them are random and 1 is the correct answer ? (Codepen inclu
  • getting perplexed about this code, not seeing any thing wrong, but not printing out what i'm expecting
  • Ajax.beginForms MVC Partial View
  • Mouse-wheel direction not working
  • vanilla js remove id box
  • How to change text to upper case or lower case depending on string length in Angular 1.5?
  • issues with autocomplete inputs values
  • Angular 2/Typescript Delete Object On Button Click
  • Angular 2 ngFor can't show one object by index
  • The HTML Form of my website don't send the infos anywhere
  • Returning value from one method to second in callback within object
  • KonvaJS: How to serialize object with custom property?
  • What are the reasons for use static contextTypes = {} in react components?
  • element.changedTouches[0] error undefined. Chrome bug?
  • Focus issue of cursor on Internet Explorer
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com