I am having firestore collection but filter query not working as expected but it's abominably its work when i filter from firebase Database UI.
Code:
const docBookingRef = firestore().collection("booking").where("parentCase", "array-contains-any", [66])
docBookingRef.get().then((doc) => {
const list = [];
doc.forEach(function (docV) {
list.push(docV.data());
});
console.log('booking list', list);
}).catch(function (error) {
console.log('booking error', error);
})
I am unable to recreate the problem in this JSBin. My collection has a single document with an array field parentCase and a single value 66 in there.
Aside from that, but code is a pretty direct copy of yours:
const query = root.where("parentCase", "array-contains-any", [66])
query.get().then((doc) => {
const list = [];
doc.forEach(function (docV) {
list.push(docV.data());
});
console.log('booking list', list);
}).catch(function (error) {
console.log('booking error', error);
})
Are you sure your array contains a numeric value, and not a string "66"? For the latter case, the query would have to be: where("parentCase", "array-contains-any", ["66"]).
Related
I'm trying to get all messages in a chat. Each doc has a "messages" array, which maps to message body, createdAt, and sender's username. There is a second array for all users in chat.
How do I return all of the last 10 elements of the messages array?
Code:
exports.getChat = (req, res) => {
let chatData = {};
db.doc(`/chats/${req.params.chatId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: "Chat not found." });
}
chatData = doc.data();
chatData.chatId = doc.id;
return db
.collection("chats")
.where("chatId", "==", req.params.chatId)
.get();
})
.then((data) => {
chatData.messages = [];
data.forEach((doc) => {
chatData.messages.push(doc.data());
});
return res.json(chatData);
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: err.code });
});
};
The code I have so far returns an empty messages array.
When querying Firestore, it's not possible to instruct the query to filter items out of an array field. You have to read the entire array field, then decide what you want to do with the items in that array. So, this means that a second query is not helpful here. You have everything you need in the first document snapshot.
db.doc(`/chats/${req.params.chatId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: "Chat not found." });
}
const chatData = doc.data();
// chatData now contains the entire contents of the document in the screenshot
const messages = chatData.messages
// messages now contains the entire array of messages - use however many want
})
How can I get the values of the searched objects?
const query = new Parse.Query(Parse.User);
query.equalTo("sexo", "feminino");
query
.find()
.then(results => {
console.log(results.get("username"));
})
.catch(error => {
console.log(error);
});
TypeError: "results.get is not a function"
How to get values of a search query in Parse server ?
Query.find will be able to fetch the results of your queries.
As you can have multiples results, the object that you get is an array of elements
so if you want to display the name of all users of your query you'll have to iterate to display all of your users.
const query = new Parse.Query(Parse.User);
query.equalTo("sexo", "feminino");
query
.find()
.then(results => {
results.forEach(user => {
console.log(user.get("username"))
});
})
.catch(error => {
console.log(error);
});
If you want to have examples of queries click here
Hope my answer help you 😊
I'm trying to get data from my database hierarchy db.collection/doc/collection/
I need to get the data from the collection "product"
I can already filter out the right document, by using this snippet.
Still, didn't manage to get any data from the next collection.
db.collection('deliveryservice').where('owner_id', '==', user.uid).collection('product').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
Please try the following way to retrieve data from your product collection.
var docRef = db.collection("deliveryservice").doc(user.uid).collection('product');
docRef.get().then((snapshot) => {
snapshot.docs.forEach(doc => {
}
}).catch(function(error) {
console.log("Error getting document:", error);
})
I have a parent collection categories and it child collection directories
Directories connected with Categories via Category property
I want to query all directories with category equal to level
this.firestore
.collection<any>('directories', ref => ref.where('categories', '==', 'levels'))
.get()
.pipe(
map(x => {
const out: [] = [];
x.forEach(y => {
out.push(y.data());
});
return out;
})
);
I am getting an empty array in return. How would you fix that?
UPDATE based on the answer provided by #renaud-tarnec:
const categoryDocRef = this.firestore.doc('categories/levels');
this.firestore
.collection<any>('directories', ref => ref.where('categories', '==', categoryDocRef))
.get()
.pipe(
map(x => {
const out: [] = [];
x.forEach(y => {
out.push(y.data());
});
return out;
})
);
Now having an error core.js:15713 ERROR Error: Function Query.where() called with invalid data. Unsupported field value: a custom AngularFirestoreDocument object
If you want to use the DocumentReference data type in a query, you have to build a DocumentReference and use it in your query, as follows (in "standard" JavaScript):
const categoryDocRef = firebase.firestore().doc('categories/levels');
firebase.firestore().collection("directories").where("parent", "==", categoryDocRef)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
I've made the assumption that the documents containing the field parent (which , in turn, contains the DocumentReference type data) are in a collection named directories.
UPDATE: It appears that the following won't work with angularFire2, see the comments
So, if I am not mistaking, this would be done as follow in angular, based on the code of your question:
const categoryDocRef = this.firestore.doc('categories/levels');
this.firestore
.collection<any>('directories', ref => ref.where('parent', '==', categoryDocRef))
.get()
...
How can I perform a simple search in Firebase Firestore to check if a record exists in a collection? I've seen this code in the documentation, but it is not complete.
// Create a reference to the cities collection
var citiesRef = db.collection('cities');
// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');
In my use case I want to check the rejected contacts collection for a given number. This is my code
const collectionRef = db.collection('rejectedContacts');
const queryRef = collectionRef.where('contact','==',phone);
let contactRejected: boolean = queryRef.get.length>0 ;
if (contactRejected) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
}
I've checked the function with a rejected number, which i added manually in the collection, but it is not responding with the rejected message. How can I get the count or the row itself with a select query. What is wrong with my code?
UPDATE 1
As #Matt R suggested, I updated the code with this
let docRef = db.collection('rejectedContacts').where('contact', '==', phone).get();
docRef.then(doc => {
if (!doc.empty) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
} else {
return response.json(
{
status: 0,
message: `Contact , ${phone} is not blocked`,
result: null
});
}
})
.catch(err => {
console.log('Error getting document', err);
});
But when checked with the existing number, it is returning with not blocked
Edit 2
return collectionRef.select('contact').where('contact', '==', phone).get()
.then(snapShot => {
let x : string = '['
snapShot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
x+= `{${doc.data}},`;
});
return response.send(x);
});
It is only returning the value of x from this line
let x : string = '['
Firestore's get() method returns a promise and response, I would try in this format to handle whether the document exists or not. This format may also lend better error messages when troubleshooting.
EDIT / UPDATED: Using the where clause returns a snapshot that must be iterated through, because it can return multiple documents. See documentation here: https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection
Updated code with your example.
var collectionRef = db.collection('rejectedContacts');
var query = collectionRef.where('contact','==',phone).get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});