Firestore query returning empty snapshot - javascript

I have a node websocket listener set to query some data from my database. Currently however the query returns an empty snapshot even though I know that the query should return something.
I'm making a simple node based forum (although I'm pretty new to Node so it's not that good lol) and I'm trying to query post data from the server to send back to the client. I've tried checking to see if my post references were correct and double checked that the values I'm querying exist within the collection. I've also already checked that the data was sent through the socket correctly so I'm at a loss.
let query = db.collection('posts').where('id','==',postID);
query.get().then(snapshot => {
if (snapshot.empty) {
client.emit('resPost', 'Failed');
return;
}
snapshot.forEach(doc => {
console.log(doc.data());
client.emit('resPost', doc.data());
});
});
When I load the post page I get the response tied to the empty snapshot.
Edit: As suggested by #Phil I've included a log for the postID variable.
console.log('postID', typeof postID, JSON.stringify(postID))
Output:
postID string "0"
Here's a screenshot of the console if needed. The ClientID is the ID of the websocket connection.
https://imgur.com/a/MdtwEvu

I'm quite surprised there isn't a duplicate question anywhere but here's your answer...
Firestore's query equality conditionals are type-sensitive. If your collection property is an integer, you need to compare it to an integer instead of a string.
For example
db.collection('posts').where('id', '==', parseInt(postID, 10))

Related

Best way to batch create if not exists in firestore

I am working with a project where we create a bunch of entries in firestore based on results from an API endpoint we do not control, using a firestore cloud function. The API endpoint returns ids which we use for the document ids, but it does not include any timestamp information. Since we want to include a createdDate in our documents, we are using admin.firestore.Timestamp.now() to set the timestamp of the document.
On subsequent runs of the function, some of the documents will already exist so if we use batch.commit with create, it will fail since some of the documents exist. However, if we use batch.commit with update, we will either not be able to include a timestamp, or the current timestamp will be overwritten. As a final requirement, we do update these documents from a web application and set some properties like a state, so we can't limit the permissions on the documents to disallow update completely.
What would be the best way to achieve this?
I am currently using .create and have removed the batch, but I feel like this is less performant, and I occasionally do get the error Error: 4 DEADLINE_EXCEEDED on the firestore function.
First prize would be a batch that can create or update the documents, but does not edit the createdDate field. I'm also hoping to avoid reading the documents first to save a read, but I'd be happy to add it in if it's the best solution.
Thanks!
Current code is something like this:
const createDocPromise = docRef
.create(newDoc)
.then(() => {
// success, do nothing
})
.catch(err => {
if (
err.details &&
err.details.includes('Document already exists')
) {
// doc already exists, ignore error
} else {
console.error(`Error creating doc`, err);
}
});
This might not be possible with batched writes as set() will overwrite the existing document, update() will update the timestamp and create() will throw an error as you've mentioned. One workaround would be to use create() for each document with Promise.allSettled() that won't run catch() if any of the promise fails.
const results = [] // results from the API
const promises = results.map((r) => db.doc(`col/${r.id}`).create(r));
const newDocs = await Promise.allSettled(promises)
// either "fulfilled" or "rejected"
newDocs.forEach((result) => console.log(result.status))
If any documents exists already, create() will throw an error and status for that should be rejected. This way you won't have to read the document at first place.
Alternatively, you could store all the IDs in a single document or RTDB and filter out duplicates (this should only cost 1 read per invocation) and then add the data.
Since you prefer to keep the batch and you want to avoid reading the documents, a possible solution would be to store the timestamps in a field of type Array. So, you don't overwrite the createdDate field but save all the values corresponding to the different writes.
This way, when you read one of the documents you sort this array and take the oldest value: it is the very first timestamp that was saved and corresponds to the document creation.
This way you don't need any extra writes or extra reads.

Firestore orderBy and where filters not working together

If I query my users collection and filter by 2 different properties as seen below, it returns the expected data.
return this.afs
.collection<Employee>('users', ref => {
return ref
.where('accountId', '==', accountId)
.where('isEmployee', '==', true);
})
.valueChanges()
However, if I try to order that data by name, as seen below, it returns an empty array.
return this.afs
.collection<Employee>('users', ref => {
return ref
.where('accountId', '==', accountId)
.where('isEmployee', '==', true)
.orderBy('name');
})
.valueChanges()
I figured I must need to manage the way indexing is being handled or something, but did some research and my understanding is that if that were the case, I would get an error message in the console with a link to setup the composite indexing that I need. I don't get any errors though, just an empty array. What am I doing wrong? Is it possible to order a collection of data that is filtered by 2 properties? I believe I am using Firebase version 6.5, but am willing to update if that will solve my problem.
I would get an error message in the console with a link to setup the composite indexing that I need.
Yes, that's correct. When you are using a query like yours, a warning message should be displayed in the console.
I don't get any errors though, just an empty array.
In this case, you should create that index manually in the Firebase console.
Is it possible to order a collection of data that is filtered by 2 properties?
Sure it is. Just create the required index and then you should be able to execute the query.
It doesn’t look like you’re ready to catch errors. May want to do something like:
.catch(error => console.log(error)
(Will format that when on desktop)

Cloud FireStore: Retrieve 1 document with query

I'm trying to retrieve a single document from a collection. I'm now using the code below that returns a collections of items, but I know that there is only one item. So it ain't that clean.
Setup:
private db: AngularFirestore
private itemSubs: Subscription[] = [];
itemAd= new Subject<Item>();
fetchItemFromDatabase(itemId: string) {
this.itemSubs.push(
this.db.collection('items', id => id.where('itemId', '==', itemId)).valueChanges().subscribe((items: Item[]) => {
this.itemAd.next(items);
}));
}
I tried to do it with this.db.collection('items').doc(itemId).get() , but I'm getting an error on get() that it's not found/supported. I also didn't got autocompletion when trying to call this methode (methode found in the official cloud firestore documents).
I looked at around at some other solutions and then tried it with this.db.collection('items').doc(itemId).ref.get().then(...) , but here I got an empty doc back.
So I'm a bit stuck at the moment and I don't want to use that whole collections logic when I know there is only 1 item in it.
There may be multiple documents with itemId equal to a given value. While you may know that there is only one in your app, the database and API cannot know nor enforce that. For that reason the query you run will always return a query snapshot that potentially contains multiple documents.
this.db.collection('items', id => id.where('itemId', '==', itemId))
If you want to enforce that there is only one document with the given item ID, consider using that item ID as the document name instead of storing it as a field in the document.
There can be only one document with a given name, so that means the ID is guaranteed to be unique. And you can then retrieve that document with:
this.db.collection('items').doc(itemId)

Trying to get a snapshot of a variable from firebase gives me an error

Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})

Mongo DB - Why my Users.findOne is Undefined?

I'm working on Meteor, trying to find some values from Mongodb collection.
here is the code:
var sameLogins = Users.findOne({login: 'a'});
console.log(sameLogins);
But it's returning and "undefined".
But record exists in collection:
So, can anybody tell what I'm missing?
Also, in mongo console - everything is working fine:
I was looking in Publish/Subsribe stuff, but i'm using autopublish module yet.
Thank you!
I will leave the answer for this issue for new users having the same problem.
If you're using autopublish package then you should be aware that it's publishing the result of .find() for every collection.
But, Meteor.users.find(), be default, will return only _id and profile fields, so documents in your Meteor.users client collection will have these two fields only.
The most easy workaround for this would be to create your own publication (allUsers, for example) and in it to return those fields you need:
Server:
Meteor.publish('allUsers', () => {
// check for Meteor.userId() is omitted, put it here, if needed
return Meteor.users.find({}, { fields: { ... } });
});
Don't forget to subscribe to it:
Client:
Meteor.subscribe('allUsers');
Update for Meteor:
Right now you are storing a cursor in your variable sameLogins. In order to retrieve the results you want, you must actually execute this query by either calling fetch(). What is returned from findOne without fetch is essentially an object that you could use to iterate over and find mongoDB documents - (called a collection cursor). The cursor is not your result itself.
Calling fetch would like something like:
Users.findOne({login: 'a'}).fetch()

Categories

Resources