Title says it all, when I try to get a document by id from Firestore using code:
firestore
.collection("my_collection")
.get("foo")
.then((snapshot) => {
snapshot.forEach((doc) => {
const data = doc.data();
console.log(doc.id, data);
});
})
.catch((err) => {
console.log("Error getting documents", err);
});
It throws me this error:
FirebaseError: FirebaseError: Function Query.get() requires its first argument to be of type object, but it was: "foo"
So I supplied an object with an id: {id: "foo"}
which gave me another error:
FirebaseError: FirebaseError: Unknown option 'id' passed to function Query.get(). Available options: source
How can I get a document from collection by id?
Title says it all, when I try to get a document by id from Firestore using code:
firestore
.collection("my_collection")
.get("foo")
.then((snapshot) => {
snapshot.forEach((doc) => {
const data = doc.data();
console.log(doc.id, data);
});
})
.catch((err) => {
console.log("Error getting documents", err);
});
It throws me this error:
FirebaseError: FirebaseError: Function Query.get() requires its first argument to be of type object, but it was: "foo"
So I supplied an object with an id: {id: "foo"}
which gave me another error:
FirebaseError: FirebaseError: Unknown option 'id' passed to function Query.get(). Available options: source
How can I get a document from collection by id?
Share Improve this question edited Jan 18, 2024 at 13:23 soundflix 2,86312 gold badges16 silver badges34 bronze badges asked Aug 3, 2019 at 7:52 N NN N 1,6384 gold badges28 silver badges46 bronze badges2 Answers
Reset to default 5The get
method of firestore doesn't accept any argument.
You need to pass your id with the doc
method, as stated here
firestore.collection('my_collection').doc('foo').get()
.then(snapshot => {
snapshot.forEach(doc => {
const data = doc.data();
console.log(doc.id, data);
});
})
.catch(err => {
console.log('Error getting documents', err);
});
Get the id
and assign to a new {key: value}
See code below
const newProducts = [];
firestore()
.collection("products")
.where("category", "in", categories)
.get()
.then((docs) => {
docs.forEach((doc) => {
const data = doc.data();
// adding new property id with id from Firestore
data.id = doc.id;
newProducts.push(data);
});
setProducts(newProducts);
})
.catch((err) => console.log(err));