logo
down
shadow

Firestore: How to get random documents in a collection


Firestore: How to get random documents in a collection

By : eric engstrom
Date : October 18 2020, 01:08 AM
wish helps you Using randomly generated indexes and simple queries, you can randomly select documents from a collection or collection group in Cloud Firestore.
This answer is broken into 4 sections with different options in each section:
code :
let postsRef = db.collection("posts")
queryRef = postsRef.whereField("random", isGreaterThanOrEqualTo: random)
                   .order(by: "random")
                   .limit(to: 1)
let postsRef = db.collection("posts")
queryRef = postsRef.whereField("random", isGreaterThanOrEqualTo: lowValue)
                   .order(by: "random")
                   .limit(to: 1)
queryRef = postsRef.whereField("random", isLessThanOrEqualTo: random)
                   .order(by: "random", descending: true)
                   .limit(to: 1)

queryRef = postsRef.whereField("random", isGreaterThanOrEqualTo: random)
                   .order(by: "random")
                   .limit(to: 1)
{'random': {'1': 32456, '2':3904515723, '3': 766958445}}


Share : facebook icon twitter icon
Flutter Firestore: specific documents from a collection (Firestore.collection.where)

Flutter Firestore: specific documents from a collection (Firestore.collection.where)


By : Kaustubh
Date : March 29 2020, 07:55 AM
I wish this helpful for you Firebase does not support logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
How to push all the documents in a collection with values to another collection in form of map firestore web

How to push all the documents in a collection with values to another collection in form of map firestore web


By : Timothy Monteath
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have products in my cart which on checkout get converted to orders. I want all the documents in cart collection to be mapped as an object map / array in orders collection inside a single document. , Order item IDs => Array field:
code :
...
.get()
.then(snapshot => {
    const ids = snapshot.docs.map(doc => doc.id)

    db.collection('users')
        .doc(uid)
        .collection('orders')
        .doc()
        .set({items : ids})
}
...
.get()
.then(snapshot => {
    const batch = db.batch()
    const orderRef = db.collection('users').doc(uid).collection('orders').doc()
    const cartRef = db.collection('users').doc(uid).collection('carts').doc(item_key)

    batch.set(orderRef, { 
        // order fields
    })

    snapshot.forEach(docSnap => {
        batch.set(orderRef.collection('order_items').doc(docSnap.id), {
            // order item fields
        })
    })

    batch.delete(cartRef)
    batch.commit()
}
Firestore Nested Documents with random ID inside a collection document

Firestore Nested Documents with random ID inside a collection document


By : flipbug
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Currently you wish to store a user's pets at /pets/userId. To add each pet at this location, you would need to use a subcollection as documents can't hold other documents. The following code adds a pet that will be stored at /pets/userId/pets/somePetId.
code :
addPet(ownerName, petName, type, breed, size){
    let user = this.afAuth.auth.currentUser;
    if (!user) {
      return Promise.reject({code: 'unauthenticated', message: 'user not logged in'})
    }
    return this.afs.collection("pets").doc(user.uid).collection("pets").add({
        OwnerName: ownerName,
        OwnerID: user.uid,
        PetName: petName,
        PetType: type,
        PetBreed: breed,
        PetSize: size
      });
  }
addPet(ownerName, petName, type, breed, size){
    let user = this.afAuth.auth.currentUser;
    if (!user) {
      return Promise.reject({code: 'unauthenticated', message: 'user not logged in'})
    }
    return this.afs.collection("pets").add({
        OwnerName: ownerName,
        OwnerID: user.uid,
        PetName: petName,
        PetType: type,
        PetBreed: breed,
        PetSize: size
      });
  }
function getPetsForCurrentUser() {
  let user = this.afAuth.auth.currentUser;
  if (!user) {
    return Promise.reject({code: 'unauthenticated', message: 'user not logged in'})
  }
  return this.afs.collection("pets").where("OwnerID", '==', user.uid).get()
    .then(childrenAsArrayOfObjects)
}
addPet(ownerName, petName, type, breed, size){
    let user = this.afAuth.auth.currentUser;
    if (!user) {
      return Promise.reject({code: 'unauthenticated', message: 'user not logged in'})
    }
    return this.afs.collection("users").doc(user.uid).collection("pets").add({
        OwnerName: ownerName,
        OwnerID: user.uid,
        PetName: petName,
        PetType: type,
        PetBreed: breed,
        PetSize: size
      });
  }
function getPetsForCurrentUser() {
  let user = this.afAuth.auth.currentUser;
  if (!user) {
    return Promise.reject({code: 'unauthenticated', message: 'user not logged in'})
  }
  return this.afs.collection("users").doc(user.uid).collection("pets").get()
    .then(childrenAsArrayOfObjects)
}
let ragdollCatsQuery = db.collectionGroup('pets').where('PetType', '==', 'Cat').where('PetBreed', '==', 'Ragdoll');
ragdollCatsQuery.get()
  .then(querySnapshot => {
    console.log("Found " + querySnapshot.size + " cats with the breed: Ragdoll");
  })
function childrenAsArrayOfObjects(querySnapshot, idFieldName) {
  let idFieldName = (idFieldName && idFieldName + "") || "id";
  let children = [];
  querySnapshot.forEach(childDoc => {
    children.push({...childDoc.data(), [idFieldName]: childDoc.id})
  }
  return children;
}
.then(querySnapshot => childrenAsArrayOfObjects(querySnapshot, "PetID"))
Using firebase cloud function to copy all documents from a master collection in Firestore to new sub-collection

Using firebase cloud function to copy all documents from a master collection in Firestore to new sub-collection


By : user3664887
Date : March 29 2020, 07:55 AM
Hope that helps If I am not mistaking, by correctly managing the parallel writes with Promise.all() and returning the Promises chain it should normally improve the speed.
Try to adapt your code as follows:
code :
exports.setupCollectionForUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {

        const userId = context.params.userId;

        return db.collection('master').get().then(snapshot => {  

            if (snapshot.empty) {
                console.log('no docs found');
                return null;
            } else {

                const promises = [];
                const slaveRef = db.collection('users').doc(userId).collection('slave');
                snapshot.forEach(doc => {

                      promises.push(slaveRef.doc(doc.get('uid')).set(doc.data()))

                });

                return Promise.all(promises);

            }

        });

    });
Firestore 'get' query for all documents in a collection returns no documents

Firestore 'get' query for all documents in a collection returns no documents


By : Neil Hodgson
Date : March 29 2020, 07:55 AM
this one helps. First of all, you are reaching into the snapshot object using private properties:
code :
snapshot._docs
Related Posts Related Posts :
  • UTC to local time conversion not working in Swift 2
  • Angle between 2 Lines in 3D
  • Cannot convert value of type URL.Type to expected argument type 'URL'
  • Mismatching types when trying to assign to optional property
  • The type of self in Swift and its use with respect to two-phase initialization
  • How to Filter a search using key words in Swift
  • Swift Package Manager (SPM): Error importing library
  • ARKit – Ball is not passing through "SCNTorus" hole
  • AVAssetExport fails "cannot decode"
  • Carthage: Multiple build commands for output file framework
  • add last custom collectionViewcell to collectionView swift 3
  • iOS silent push not work when APP in background
  • Set Variable of Launcher View Controller on Task Completion
  • Scroll an NSTextView to bottom after adding text
  • UICollectionView Video Performance
  • Finding The First Non-repeating Character algorithm Swift 4 (Looping over string only once)
  • Playing music in Swift: Unexpectedly found nil while unwrapping an Optional value
  • NSImage Getting Resized when I draw Text on it
  • Firebase Firestore - OR query alternative
  • Misplaced Information on 2 PickerView
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com