How to make a request to receive random documents based on id? limit(10) - google-cloud-firestore

Firestore(web)
Help me write a request for random documents based on ID
Can I do this without getting the entire collection?
const questions = [];
const docRef = db.collection('ru').doc(category).collection('questions');
try {
const doc = await docRef.get();
doc.forEach((item) => {
questions.push(item.data());
});
} catch (e) {
throw e;
}

Related

How can I loop over a list of documents and execute commands on each in mongoose with async await

I have users, posts and follows collection. I want to select posts, limit it to 10 and look their authors in follows collection whether user follow him or not. Also using async and await made me confusing. I tried this code
async function index (req,res){
const {user_id} = req.body
const post = await Post.find().exec( async (err,doc)=>{
const isFollowing = await Follows.find({who_id : user_id , whom_id : doc._id })
if (isFollowing.length > 0){
return doc
}
})
Then I figured out from VS Code that if I use exec function "'await' has no effect on the type of this expression.
You can select 10 random posts and return only the one that the user follows between them with:
async function index (req,res)
{
const { user_id } = req.body
const posts = await Post.find().limit(10);
const following = [];
for (const post of posts) {
const isFollowing = await Follows.find({ who_id : user_id , whom_id : post._id });
if (isFollowing) following.push(post);
}
return following;
})

How to fetch data and update it from firebase

I am having trouble trying to fetch data from firebase and updating the values from it.
I have a restaurant name and the number of times it has been picked (user chooses to go to that restaurant to eat). I am trying to retrieve the numPicked and update it by adding one if the user decides to go there again.
Here i am trying to fetch ONE specific document and trying to store the docID and the variables I need to update.
docID = doc.id; docID is return NULL
meaning that the foreach loop isn't even being read.
Future<bool> searchQuery(
{required String restaurantName,
required var userID,
required db}) async {
int addOne = 1; //addes one if it has been picked
//this is not working
try {
Query query2 =
db.where('userId', isEqualTo: FirebaseAuth.instance.currentUser!.uid);
Query query = query2.where('restaurantName', isEqualTo: restaurantName);
await query.get().then((querySnapshot) {
// ignore: avoid_function_literals_in_foreach_calls
querySnapshot.docs.forEach((doc) {
docID = doc.id;
numPicked = doc['numPicked'];
restaurantExist = true;
});
}).catchError((error) {
// print('error querying: #error');
});
} catch (ex) {
// ignore: avoid_print
print(ex);
}
//this is not working
int totalPicked = numPicked + addOne;
//if the restaurant exist then update the numpicked for that specific restaurant
if (restaurantExist) {
try {
var query = db
//.collection('NumRestaurantPicked')
.doc(docID);
await query.update({'numPicked': totalPicked.toString()});
} catch (ex) {}
}
return restaurantExist;
}
The docID and numPicked variables are not defined in the method signature, so they are not accessible outside of the try block. They should be defined as class variables, so they can be accessed from other methods.

Can't fetch data with react-query

On my client-side(React js), I want to fetch data from the backend. But it's not working. The output of data is undefiend. Code Snippets
const url = `http://localhost:5000/items/${id}`;
const { data } = useQuery("data", () => axios(url));
console.log("data", data);
In the backend, I am using Express js and MongoDB as databases.
Try creating a function for fetching, for example:
const fetchData = async (id) => {
try {
const URL = `http://localhost:5000/items/${id}`;
const response = await axios.get(URL);
return response;
} catch(error) {
console.log(error);
}
}
Then:
const { data } = useQuery("data", () => fetchData(id));
You have to provide the id to fetchData

Mongoose find return an empty array but return values when i set a variable to the model

why is the first query not working
I am using mongoose
i want to e able to check for errors during query that why I want to use the first instance
import Work from './WorkModel.js'
const response = await Work.findOne({ user: userId}).exec((err, result) => {
if (err) {
throw new Error('Try again later');
} else {
console.log(odemruId);
return result;
}
});
return response
//this return no value
const response= await Work.findOne({user: userId})
return response
//this actual works
```

How to fetch documents coming from different collections in Firestore inside a Redux Saga

I have the following saga:
export function* fetchAnalyticsData() {
try {
const data = [];
const collectionReference = firestore.collection("collection1")
const UIDSreference = yield collectionReference.get();
// getUID is a function that returns an array of UIDS of documents of collection1
const UIDS = yield call(getUID, collectionReference);
const populate = yield all(
UIDS.map((uid) => {
firestore
.collection("collection1")
.doc(uid)
.collection("collection2")
.get()
.then((response) => {
if (response.docs.length) {
response.docs.forEach((doc) => data.push(doc.data()));
console.log(data);
}
});
})
);
console.log(data);
yield put(fetchAnalyticsDataSuccess(data));
} catch (error) {
console.log(`Error in fetchAnalyticsData: ${error}`);
yield put(fetchAnalyticsDataFailure(error.message));
}
}
The inner console.log(data) prints the data array correctly filled. However, the outer console.log(data) prints an empty array. I know it's because these things are promises, but then how can I solve this issue?