Error : "No document to update " in Firestore - firebase

Im using cloudFirestore as the database and i want to update a Field that lives in a document.
collection :users.
document:user.
field:website.
so for that i did like so :
db.doc('/users/user').update({website:'user.com'});
but iam getting this Error :
No document to update: projects/social-app-12282/databases/(default)/documents/users/user'
Can someone tell me wht this happen,thank you in advance
Edit:
you can see here that i have a docment called user

For you to update a document in Firestore, the structure of the update is a little bit different in relation to yours. As per the documentation - accessible here - you need to select the collection and then, the document you want to update. The code would be something like the below one:
var usersRef = db.collection("users").doc("user");
// Set the "user" field of the city 'DC'
return usersRef.update({
"website": "user.com"
})
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
A simplified version would be:
db.collection("users").doc("user").update({
"website": "user.com"
})
.then(function() {
console.log("Document successfully updated!");
});
While this is untested code, I believe it should help you with understanding on how to update the values and as a starting point. You can get more examples from the official documentation as well.

Related

Project specific fields with Firestore? [duplicate]

Here is my data structure:
I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.
There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.
If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.
See also this thread of discussion.
It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.
This is actually quite simple and very much achievable using the built in firebase api.
let docRef = db.collection("users").document(name)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let property = document.get(field)
} else {
print("Document does not exist in cache")
}
}
There is actually a way, use this sample code provided by Firebase itself
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let property = document.get('fieldname')
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I guess I'm late but after some extensive research, there is a way in which we can fetch specific fields from firestore. We can use the select keyword, your query would be somthing like (I'm using a collection for a generalized approach):
const result = await firebase.database().collection('Users').select('name').get();
Where we can access the result.docs to further retrieved the returned filtered result. Thanks!
//this is code for javascript
var docRef = db.collection("users").doc("ID");
docRef.get().then(function(doc) {
if (doc.exists) {
//gives full object of user
console.log("Document data:", doc.data());
//gives specific field
var name=doc.get('name');
console.log(name);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

In Firebase how do we add more fields to a document through flutter?

I'm not sure how to add an extra field to a firestore document through code. I do not want to create new fields through firebase console, since these field names will be dynamic and be used for searching. EX: if a field does "NOT" exist, add to result. (Since firestore does not allow negation queries.
In Cloud_Firestore#0.14.0, there has been many changes.
"setData/set now supports SetOptions to merge data/fields (previously this accepted a Map)"
Now, for this you need to do it as follows:
FirebaseFirestore.instance.collection('collectionName')
.doc('docID')
.set({
'field': 'value'
},SetOptions(merge: true)).then((value){
//Do your stuff.
});
firestore.instance.collection('yourDbCollection').doc('ifYourIdCostumized').update({
field: newItem
})
.then(function () {
console.log("Document successfully updated!");
}).catch(function (error) {
console.error("Error removing document: ", error);
});
firestore.instance.collection("collectionName").document("documentID").setData({field : value }, merge: true).then((onValue){//your other code}
This Code will work.
Use setData and use merge: true as shown in the above code snippet.

Firebase query download the whole database. Why?

I try to download and show only specific data from the Realtime Database. I have the following code:
getUserPlatformIos() {
this.dataRef = this.afDatabase.list('data/users', ref => ref.orderByChild('meta/platform').equalTo('ios'));
this.data = this.dataRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
return this.data;
}
My firebase database structure
Firebase rules
Why firebase does download the whole database if I query before? This causes very long loading times and a lot of downloaded data....
Indexes need to be defined at the place where you the query. Since you run the query on data/users, that's where you need to define your index:
"users": {
".indexOn": "meta/platform"
}
This defines an index on users, which has the value of the meta/platform property of each user.
Note that the log output of your app should be showing an error message with precisely this information. I highly recommend checking log output whenever something doesn't work the way you expect it to work.

Firestore query only needed fields (Firebase) [duplicate]

Here is my data structure:
I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.
There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.
If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.
See also this thread of discussion.
It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.
This is actually quite simple and very much achievable using the built in firebase api.
let docRef = db.collection("users").document(name)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let property = document.get(field)
} else {
print("Document does not exist in cache")
}
}
There is actually a way, use this sample code provided by Firebase itself
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let property = document.get('fieldname')
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I guess I'm late but after some extensive research, there is a way in which we can fetch specific fields from firestore. We can use the select keyword, your query would be somthing like (I'm using a collection for a generalized approach):
const result = await firebase.database().collection('Users').select('name').get();
Where we can access the result.docs to further retrieved the returned filtered result. Thanks!
//this is code for javascript
var docRef = db.collection("users").doc("ID");
docRef.get().then(function(doc) {
if (doc.exists) {
//gives full object of user
console.log("Document data:", doc.data());
//gives specific field
var name=doc.get('name');
console.log(name);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

Why are non auto-generated document Ids are in italics in Firestore console?

When i add a document with my own document Id (not auto generated), document Id node is in italics as shown in the screenshot from Firestore console. What is the reason behind this?
My code to add data is
const billingRef = db
.collection('billing/test/2017/months/11')
.doc();
billingRef
.set({ name: 'ABC' })
.then(_ => {
console.log('saved');
})
.catch(err => {
console.log(err);
});
Above code adds a node successfully, but adds node "test" and "months" in italics.
screenshot 1
screenshot 2
screenshot 3
My query yields zero results for such records in firestore, following code. How can I query all the nodes under billing?
db.collection("billing").get().then(function(querySnapshot) {
console.log(querySnapshot.size) // this is always 0
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
});
Following up on my comment above you will see in the Firestore console that for Documents in italic there is a small text saying "This document does not exist, it will not appear in queries or snapshots", for non-italic it says "This document has no data", so the intuition is that when the Document is created in code without any Fields then it is "null" (a subcollection does not count). If a Field is added and removed, then the Document is simply empty and not null.
Since your query for the Documents under billing are in italic ("null" or does not exist), as the text above states, they will not appear in queries.
The solution would be to either add the document through the Firestore console because here Documents are created as empty, or if in code, add a Field and maybe remove it again if not needed, then the Documents will appear in queries.
The problem, I later came to find from this Question's answer for me was creating a sub collection to an empty document. This was my code that was bringing up grayed out documents.
db.collection('temporal')
.doc('documentexample')
.collection("files")
.add({
name: "Lorem"
})
.catch((error) => {
console.error("Error adding file: ", error);
});
In the above code the doc documentexample had no field in it. So the code goes ahead and creates documentexample (it has no fields) then creates a subCollection in it files. This according to firebase just grays out the first document documentexample.
The workaround to this is first create the document add a field in it then create a subcollection to it and on and on... For my use-case, I created a function that creates the document and adds a field to it when the user signs up for the first time

Resources