Firebase get document collection based on specific field using angular - javascript

I want to get collection data based on UserId field .
getData(){
const data$ = this.fbs.collection(this.trackerData,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotChanges().subscribe(res=>{
console.log(res);
});
}
if i get data like this i am getting response as :-
but i need response data like :-

You need to transform your stream to get what you want:
getData(userId: string){
return this.fbs.collection(
this.trackerData,
ref=> ref.where('UserId','==',userId)
).snapshotChanges().pipe(
map(action => {
const data = action.payload.data();
const id = action.payload.id;
return { id, ...data };
})
);
}
getData("WrKDk0XSNjU20FI0EVRvADzvNHz1").subscribe(res=> console.log(res));

Related

Javascript Access an an Object in an Array

I'm fetching data from MongoDB, and the response is coming through fine, however it appears to be wrapped in array when it comes out of the User.find() function.
For example, one response is:
[{"_id":"62fe3c888e2776ef3c1a010f","username":"Drago D Trial","password":"U2FsdGVkX1867hs26KL0KitTGhWnP9tdVX6AcmI5pWE=","fullname":"Drago DaTrial","firstname":"","surname":"","email":"drago#hotmail.com","position":"QA Tester","userImage":"","locationCity":"","country":"","role":"","company":"","emailAuthorised":true,"professionalBio":"","positionRecentTitle":"","positionRecentCompany":"","companyAuthorised":"","isAdmin":false,"createdAt":"2022-08-18T13:20:08.045Z","updatedAt":"2022-08-18T13:21:02.619Z","__v":0}]
I'm accessing this through an api like this:
router.get('/inviteToJoinTeam/:token/:email', async (req, res) => {
try {
//verify the token against DB
const userToken = (req.params.token)
const indivEmailAdd = (req.params.email)
// creating user auth
try{
const userDetails = await User.find({email: indivEmailAdd})
const indivIDAdd = await userDetails (!want to access the data here and just get ID)
res.send(indivIDAdd)
}catch{
console.log('failure')
}
} catch (e) {
res.send('This isnt working');
}
});
How would you access this and just get the _id field out?
If there is only one item in the array then - simply get the id property of the first item intthe returned array
const indivIDAdd = await userDetails[0]['_id'];
or using dot notation
const indivIDAdd = await userDetails[0]._id;
if there are multiple results then map over the results and get the id from each
const ids = await userDetails.map(user => user._id);
just use response[0]._id
Ps: Response is the array coming from the database
Try projection for the same it should work
const userDetails = await User.find({ email: indivEmailAdd }, { _id : 1 })
it will return array of ObjectId. if you need to get only one object then use findOne instead of find.
According to me you have 2 solutions :
Option 1 use findOne instead of find :
const userDetails = await User.findOne({email: indivEmailAdd});
Option 2 access array / object with basic js:
const usersDetails = await User.find({email: indivEmailAdd});
const userDetails = usersDetails.at(0)._id; // or
const userDetails = usersDetails[0]['_id'];

Use GET to return records based on nested fields

I am trying to retrieve records based on a value in a mongo dataset that is in a nested object.
data is an object and documentId is a field within it and I want to retrieve just the objects within data that have the documentId of "5da713edf0a1645ae95b11oo"
I tried this code
const res = await axios.get('/api/card',{
params:{
data:documentId: "5da713edf0a1645ae95b11oo"
}
});
but it just returns all the records
Try one of these:
const res = await axios.get('/api/card',{
params:{
documentId: "5da713edf0a1645ae95b11oo"
}
});
This would be a GET request to /api/card?documentId=5da713edf0a1645ae95b11oo
or
const res = await axios.get('/api/card',{
params:{
data: {
documentId: "5da713edf0a1645ae95b11oo"
}
}
});
This would be a GET request to something like /api/card?data=%7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D
...where %7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D is URL encoded version of {"documentId":"5da713edf0a1645ae95b11oo"}
according to the documentations it says that we can not do what you have done.
axios.get('/api/card')
.then((res) => {
const data = res.data.id;
//handle your response here.
//can write your logic to retrieve your specific data
});
for further in formations refer this doc
I'm going to assume the data you're receiving on the response is an array of objects. You can filter through it. You're going to have to loop through the data though.
const res = await axios.get('/api/card')
const filteredData = res.data.filter((item) => item.documentId === '5da713edf0a1645ae95b11oo')
You can try this:
data_get() {
axios.get('/api/card')
.then((res) => {
this.setState({
documentId: res.data.id, //5da713edf0a1645ae95b11oo
});
});
}

How to retain the order of items (from server) for a key-index object after normalizing?

I am working on a react asp.net application. From the server, I return a list of items, ordered by date. Then, I normalize it using normalizr:
axios.get(url, { params: { userId, submissionId } })
.then(response => {
const notifications = new schema.Entity('notifications');
const normalizedData = normalize(response.data, [notifications]);
dispatch(
fetchNotificationsSuccess(normalizedData.entities.notifications)
);
})
.catch(error => { notificationDataOperationFailure(error) });
When I run this, the items are reordered by their key values starting from 1. I wonder how I can retain the order sent from the server.
You can find the order in the "result" you get, see more info here: https://github.com/paularmstrong/normalizr/issues/9

How to use the GraphQL Get query from aws in React

I'm trying to make use of the getquery for graphql in react.js. But I can't figure out how to go about doing this. I already succeeded to use the list query.
state = { patients: [] }
async componentDidMount() {
try {
const apiData = await API.graphql(graphqlOperation(listxxxx))
const patie = apiData.data.listxxxx.items
this.setState({ patie })
console.log(patie)
} catch (err) {
console.log('qqqqqqqqqqqqqqqqq ', err)
}
}
How does one go about using the get query? Thanks!
You need an ID to retrieve an item with any get query. getPatient(id:"YOUR ID HERE"){}`
Something like...
query Get_Patient_By_Id{
getPatient(id:"2dbcb870-e302-4ed5-a419-68751597129c"){
id
name
}
}
For React, you'll add in the id to the variables list argument:
const getPatient = await API.graphql(
graphqlOperation(
queries.getPatient,
{id: "2dbcb870-e302-4ed5-a419-68751597129c"}
)
);
console.log(getPatient.data.getPatient);
docs: https://aws-amplify.github.io/docs/js/api#simple-query

Retrieving single firestore doc in angular

I want to retrieve and display a single doc from a collection when I click on a view link. At the moment I get routed to the view page successfully but unable to display the properties of the doc I want. Here's the code I'm working with
schedule.service.ts
getSchedule(id: string) {
return this.afs
.collection("schedules")
.doc(id)
.ref.get()
.then(function(doc) {
doc.data();
console.log(doc.data()); //i see the data logged on my console correctly
});
}
then in the view.component.ts file
ngOnInit() {
this.scheduleDetail();
}
scheduleDetail() {
const id = this.route.snapshot.paramMap.get("id");
console.log(id); //I see the doc id correctly
this.schedule = this.scheduleService.getSchedule(id);
console.log(this.schedule);//I can't see the correct doc data
}
console.log(this.schedule) does not log the correct data like console.log(doc.data()) in the service.ts file does. Instead I see this
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
What is the right way of getting the doc data from my service into my component?
You have to fix with a correct usage of promise:
getSchedule(id: string) {
return this.afs
.collection("schedules")
.doc(id)
.ref.get()
.then(function(doc) {
return doc.data(); // here...
});
}
and
scheduleDetail() {
const id = this.route.snapshot.paramMap.get("id");
console.log(id);
this.scheduleService.getSchedule(id).then(data => {
console.log(data); // ... and here
});
}

Categories