I'm trying to integrate firestore into my nestjs app. When i try to retrieve data from firestore using where
clause without variable(hardcoded value) i was able to retrieve data but when i use a variable i just receive empty array.
Here is the code i try to retrieve data from firestore.
async getUserPosts(userId: number): Promise<PostsDocument[]> {
this.logger.log(`Getting posts for user with ID: ${userId}`);
const snapshot = await this.postsCollection
.where('userId', '==', userId)
.get();
const posts: PostsDocument[] = [];
snapshot.forEach((doc) => {
this.logger.debug(`Found post: ${doc.id}`);
posts.push(doc.data());
});
return posts;
}
When i replace userId
variable in where clause with 1 i was receiving data but this doesn't work.
[Nest] 1854 - 07/31/2022, 10:09:58 AM LOG [PostsService] Getting posts for user with ID: 1
I did verify that userId is received based on above log.
this is my controller code
@Get()
getUserPosts(@Query() query: { userId: number }) {
if (query.userId) {
return this.postsService.getUserPosts(query.userId);
} else {
return this.postsService.getPosts();
}
}
firebase console document screenshot for .collection("posts") .where("userId", "==", 1)
CodePudding user response:
When you use the where()
method in order to build a Query
it is very important that the value passed as third parameter is of the same type than the field declared as first parameter.
As shown in the comments under your question, after some debugging it appeared that you were passing a string as field value for a field that is of type number. Hence the empty QuerySnapshot
.
CodePudding user response:
Thanks a lot to @Renaud Tarnec and @Frank van Puffelen for helping out.
Issue: typescript number variable considered as string in while
clause.
Fix: passing userId as Number(userID)
instead of userId fixed issue
const snapshot = await this.postsCollection
.where('userId', '==', Number(userId))
.get();