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 😊
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
})
constructor(props) {
super(props);
this.state = {
users:[]
};
}
//method to get the data from users collection
async componentDidMount() {
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
}
this function returning an empty error
i want to print list of users uid
here i have users collection and inside it i have retailers collection and its document
One thing you have to realize here is that your users collection contains no documents. The document IDs are shown in italics, which means that there is no document here. The IDs are visible because there is a nested subcollection under each document. They are shown like this in the console so that you can click through and navigate to the nested subcollection, despite the document being missing.
If you want to list users with a query, you will have to actually create documents in the users collection. They can be empty if you don't have any information. But you do need actual documents in the users collection in order for anything to show up in a query.
This line in your current code querySnapshot.docs.map(doc => doc.data()) takes the data of each document. But you're keeping the UID in the ID of each document, so you'll want to use:
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.id);
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
Update: As Doug pointed out in his answer, if there are no actual user documents, your get() call will not return it.
I highly recommend creating user documents, even if it's just an empty one.
For now, the only way to get the UID would be to load all retailers for all users, and then use those results to get the ID of the parent documents:
const db = firebase.firestore();
db.collectiongroup("retailers")
.get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log("retailed "+doc.id+" for user "+doc.ref.parent.parent.id);
});
})
.catch( err =>{
console.log(err);
});
You'll have to deduplicate the UIDs, but that will leads to getting the UIDs.
But you'll be loading all retailers for all users this way, so as said, I highly recommend storing a small/empty user document instead.
The data method on querySnapshot.docs gets the data now to get the id of each document you need to add access the id property as UID is stored in id property
async componentDidMount() {
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data().id);
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
}
I have a mongoDB on an ec2 instance, I have been able to query a collection called Users successfully.
All of a sudden when I am trying to read the collection via id it returns null.
I logged into the instance and queried the database for users and there exists some orders.
I am using mongoose with the following query in my code
module.exports.readUser = function(id){
return new Promise((resolve,reject) => {
User.findOne({_id: id})
.exec()
.then(rem => {
resolve(rem);
})
.catch(error => {
reject(error.message)
})
})
}
When querying from the shell i use the following, and it works -
db.users.find({_id: ObjectId("5e89be482845434a7da45863")})
The above code should work once I am passing in a valid ObjectId String, but it fails across other collections as well.
You need to convert the id to an ObjectId, which can be simply done with:
const { ObjectId } = require('mongodb');
module.exports.readUser = function(id){
return new Promise((resolve,reject) => {
User.findOne({_id: ObjectId(id)})
.exec()
.then(rem => {
resolve(rem);
})
.catch(error => {
reject(error.message)
})
})
}
To answer why it worked before without using ObjectId ... Maybe you changed how new entries are added (i.e. maybe you had manually set the _id to a string before, but now you don't and the _id is now set automatically, which is an ObjectId by default)?
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"]).
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);
})