I have a two firebase collection "user" and "schools"
User
-> firstName
-> lastName
-> friends []-> array of reference of User Id
-> schoolRef -> reference of school
Now, I want to fetch two friends documents and two non friends documents from users collection by Passing UserId and SchoolRef Id but not able to form the query correctly.
I am fetching 4 options i.e. 4 Users from the Users Collections. 2 are friends, 2 are strangers but they all belong to same school.
export const onGetUserOptions = functions.https // }) // enforceAppCheck: true, // .runWith({
.onCall(async (data, context) => {
const MAX_TOTAL_USER_OPTION = 4;
const MAX_FRIENDS_OPTION = 2;
var db = admin.firestore();
var users = db.collection('users');
const userId = data.uid;
const schoolRef = data.schoolRef;
//fetch users document where userId reference exists in friends array
var friends = await users
.where('friends', 'array-contains', userId)
.limit(MAX_FRIENDS_OPTION)
.get();
const friendsCount = friends.docs.length;
//fetch list of non friends where uid does not exist in friends array, excluding self also
var nonFriends = await users
.where('uid', '!=', userId)
.where('friends', 'not-in', '/users/' + userId)
.where('schoolRef', '==', schoolRef)
.limit(MAX_TOTAL_USER_OPTION - friendsCount)
.get();
console.log('Non Friends: ', nonFriends.docs.toString());
//merge friends and non friends and return
const options: admin.firestore.QueryDocumentSnapshot<admin.firestore.DocumentData>[] =
[];
friends.forEach((friend) => {
options.push(friend);
});
nonFriends.forEach((nonFriend) => {
options.push(nonFriend);
});
return {
code: 200,
status: 'success',
message: 'User options fetched successfully',
data: options,
};
});