Http Post Json - Array - arrays

i am selecting a list of doctors that i want to group in a department for rural area. The selected doctors are then pushed into the array and saved to the database. i am able to selected and post to save in the database but there is a bit of flaw i am finding hard to resolve.
My problem is when i select Doctor 1 and Doctor 2 and post to my service, the params sent to my service is counted 3. That is Doctor 1, Doctor 2, Doctor 2. Why is Doctor 2 being duplicated?
selecting doctors
selectDoctors(Doctors){
Doctors.listed = (Doctors.listed) ? false : true;
this.deptList = Doctors
}
submitting group of selected doctors in array
Doctors: Doctors[] = [];
hospital = {
hospital_name : "",
details : [{
id: "",
ward: "",
}]
}
//submit data into array
Object.keys(this.Doctors).filter(key => this.Doctors[key].selected)
.forEach(key => {
this.hospital.details['0'].id = this.Doctors[key].id
this.hospital.details['0'].ward =this.Doctors[key].ward
this.groups.members.push(this.Doctors.['0']);
}
this.http.categorizeDepartment(this.groups)
.subscribe(data => {
});
}

Looks like there's some strange mutation and unnecessary methods being used here that the results are unpredictable. If all you want to do is put selected doctors into a group, you can do like this:
this.groups.members = [
...this.groups.members,
this.Doctors.filter(doctor => doctor.selected)
];
If you also want to add the doctor's info to the first item in the hospital.details array, you can add that too:
let selectedDoctors = this.Doctors.filter(doctor => doctor.selected);
this.groups.members = [...this.groups.members, selectedDoctors];
for (let doctor of selectedDoctors) {
this.hospital.details['0'].id = doctor.id
this.hospital.details['0'].ward = doctor.ward
}

Related

Find, update an element and change its index in array of objects

What I am trying to achieve here is for a Chat App where the last conversation (between the current logged in user and the target user) should update its lastMessage and be placed at the first position in the conversations array.
Here is a simpler version of the conversations array:
const conversations = [
{ ... },
{
_id: 5,
lastMessage: {
sender: 1
receiver: 2
message: 'Hello World',
conversation_id: 5
}
},
{ ... }
]
If the user with id = 1 sends a message to the user with id = 2 it should update the conversation with _id = 5 and move it to index 0 of the conversations array.
What I currently have done is moving the conversation to the top of the array but I cannot figure out how to change its lastMessage. (React reducer)
conversations: [state.conversations.find(el => el._id === action.payload.conversation_id), ...state.conversations.filter(el => el._id !== action.payload.conversation_id)]
Thanks to anyone who can help me!
Would something like this meet your requirements?
// find the first convo as you already do
const firstConversation = state.conversations
.find(el => el._id === action.payload.conversation_id);
// this is the current `lastMessage`
const lastMessage = {...first.lastMessage};
// make changes to `lastMessage` here, or assign a completely new object as required
const firstConversationUpdated = {...firstConversation, lastMessage: lastMessage};
// update state below
conversations: [firstConversationUpdated,
...state.conversations.filter(el => el._id !== action.payload.conversation_id)]

Update inventory after purchase

I have an array of objects, which means I get multiple items (products) from a database.
And I want to update after a site purchase on all products purchased inventory, download 1 from the 'nimcar' field
I'm probably having trouble accessing the objects.
I arranged the code into a whole code.
This is a process that happens on the last page after payment is received, I want to update the inventory of the products.
The process I presented here is to get from the database where the order name is listed, from a reference field containing the products it purchased, which are in the purchase basket, and the purchase basket has a reference field containing the product ID.
I was thinking about the process of getting the product ID
Hhazmana.muzarim.muzarim._id
Then update the ID to the 'nimcar' -1 field
$w.onReady(function () {
var id = $w("#dynamicDataset").getCurrentItem()._id;
wixData.queryReferenced("hazmanot", id, "muzarim")
.then((results) => {
if (results.items.length > 0) {
var firstItem = results.items
console.log(firstItem );
var myObj, i;
myObj = firstItem
for (i in myObj.muzarim) {
var id2 = myObj.muzarim
// console.log(id2);
wixData.get("muzarim", id2)
.then((item) => {
item.nimcar = Number(item.nimcar - 1)
wixData.update("muzarim", item)
.catch((err) => {
let errorMsg = err;
})
});
}
} else {
}
});
});
That's how it prints it for me:
0: "{\"muzarim\":\"7c3e8acd-a7a9-4819-b687-8b1ca06a984b\",\"_id\":\"53904a0d-c3b6-4337-b09d-b779fb0aea1e\",\"_owner\":\"ae269d04-1741-4200-bc92-2e27c7d549cd\",\"hazmanot\":\"af7ba985-f2ed-4bcf-a033-51e36b9298c1\",\"_createdDate\":\"2019-11-21T15:05:03.590Z\",\"lakoh\":\"e005f170-edcf-4694-80b7-496ab3534643\",\"_updatedDate\":\"2019-11-21T15:05:03.590Z\",\"sach\":1,\"camut\":1,\"title\":\"בית מזוזה\"}"
1: "{\"muzarim\":\"e29358d3-a74b-410a-8b41-44679f70ad05\",\"_id\":\"05b7540e-85c6-4eaa-b86b-6f4a466ed57e\",\"_owner\":\"ae269d04-1741-4200-bc92-2e27c7d549cd\",\"hazmanot\":\"3cd1eec3-c586-47b2-a1d4-2b4671c0dd2e\",\"_createdDate\":\"2019-08-21T13:43:38.884Z\",\"lakoh\":\"e005f170-edcf-4694-80b7-496ab3534643\",\"_updatedDate\":\"2019-08-21T13:43:38.884Z\",\"sach\":1200,\"camut\":1,\"title\":\"יין הסיומים\"}"
2: "{\"muzarim\":\"17a8e414-aaeb-4b0f-ae49-a4e5107ad132\",\"_id\":\"6fb545da-ac30-4304-92f9-930b49f87039\",\"_owner\":\"ae269d04-1741-4200-bc92-2e27c7d549cd\",\"hazmanot\":\"2894c50d-07e8-467e-b0f5-a37889a99fad\",\"_createdDate\":\"2019-08-21T13:41:19.197Z\",\"lakoh\":\"e005f170-edcf-4694-80b7-496ab3534643\",\"_updatedDate\":\"2019-08-21T13:41:19.197Z\",\"sach\":7200,\"camut\":1,\"title\":\"סט קדושת יצחק\"}"
3: "{\"muzarim\":\"17a8e414-aaeb-4b0f-ae49-a4e5107ad132\",\"_id\":\"a5ac5af4-03ee-4b88-9929-dc69e9dc0e04\",\"_owner\":\"ae269d04-1741-4200-bc92-2e27c7d549cd\",\"hazmanot\":\"993ed276-f7e1-4741-a038-69ad2b50cc91\",\"_createdDate\":\"2019-08-21T13:40:02.242Z\",\"lakoh\":\"e005f170-edcf-4694-80b7-496ab3534643\",\"_updatedDate\":\"2019-08-21T13:40:02.242Z\",\"sach\":7200,\"camut\":1,\"title\":\"סט קדושת יצחק\"}"

Firestore - Simple full text search solution

I know that firestore doesn't support full text search and it giving us solution to use third party services. However I found a simple solution to simple "full text search" and I think this might help others who doesn't want to use third party services as me for such a simple task.
I'm trying to search for company name which is saved in firestore collection under my companyName which can be in any format for example "My Awesome Company". When adding new company with companyName or updating a value in companyName I'm also saving searchName with it which is the same value as company name but in lower case without spaces
searchName: removeSpace(companyName).toLowerCase()
removeSpace is my simple custom function which remove all spaces from a text
export const removeSpace = (string) => {
return string.replace(/\s/g, '');
}
That turns our company name to myawesomecompany which is saved in searchName
Now I've got a firestore function to search for company which indexing through searchName and returning companyName. Minumum search value is a searched value without last character and maximum search value is a searched value with added "zzzzzzzzzzzzzzzzzzzzzzzz" transformed to lower case. That means if you search for My Aw then min value will be mya and max value will be myawzzzzzzzzzzzzzzzzzzzzzzz
exports.handler = ((data) => {
const searchValue = data.value.replace(/\s/g, '').toLowerCase()
const minName = searchValue.substr(0, searchName.length-1)
const maxName = searchValue + "zzzzzzzzzzzzzzzzzzzzzzzz"
let list = []
const newRef = db.collection("user").where("profile.searchName", ">=", minName).where("profile.searchName", "<=", maxName)
return newRef.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
list.push({ name: doc.data().profile.companyName})
})
return list
})
})
I didn't have time to fully test it but so far it works without any problems. Please let me know if you spot anything wrong with it. Now the question is
Is "z" character the highest value character in firestore or is there any other more decent way to add into the search value maximum amount without adding "zzzzzzzzzzzzz"?
I like your decision to preprocess the text so that it can be queried, but you could provide for a more flexible search by storing lowercase keywords with the users and searching those. In other words, transform:
"My Awesome Company"
to...
{ my: true, awesome: true, company: true }
...and test against that.
When adding/updating the property:
// save keywords on the user
let keywords = {}
companyName.split(' ').forEach(word => keywords[word.toLowerCase()] = true)
When querying:
let searchKeywords = userInputString.split(' ').map(word => word.toLowerCase())
let collection = db.collection("user")
searchKeywords.forEach(keyword => {
collection = collection.where(`keywords.${keyword}` , '==' , true);
});
With a little modification of previous answer I have made another simple text search. I'm saving keyword to an array instead of saving it in object like this
nameIndex: textIndexToArray(companyName)
where textIndexToArray is my custom function
export const textIndexToArray = (str) => {
const string = str.trim().replace(/ +(?= )/g,'')
let arr = []
for (let i = 0; i < string.trim().length; i++) {
arr.push(string.substr(0,i+1).toLowerCase());
}
return arr
}
which transfer a text into array. For example
"My Company"
will return
[m, my, my , my c, my co, my com, my comp, my compa, my compan, my company]
with nameIndex saved in firestore we can simply query the data thorough nameIndex and return companyName
exports.handler = ((data) => {
const searchValue = data.value.toLowerCase()
let list = []
const newRef = db.collection("user").where("nameIndex", "array-contains", searchValue)
return newRef.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
list.push({ name: doc.data().companyName, })
})
return list
})
})

Comparing items in $firebaseArray to object and removing matching items

I feel like I'm so close, but I can't figure this out.
I have a data tree in Firebase with events and under each event is a list of participants with their user id and name.
-events
-UniqueID
-participants
-userID
facebook_id: "12345678"
display_name: "John Doe"
-userID
facebook_id: "12345678"
display_name: "John Doe"
-userID
facebook_id: "12345678"
display_name: "John Doe"
In my routes I have a resolve function that queries the Facebook API for users who have my app installed and passes a friends object into the controller.
This is a page for the user to invite friends to the event. I want to check the participants array and remove users who are already in the event from the friends object.
I loop through the $firebaseArray and use lodash to find the corresponding id. Lodash's _.find returns the object if found or undefined if not found.
I found this removeItemsById function in another answer here, but it doesn't seem to work.
The _.find works correctly because I see it log the matched item, but it doesn't get removed from the object. Any ideas?
$scope.participants = $firebaseArray(firebase.database().ref().child("events").child($stateParams.eventID).child("participants"));
$scope.participants.$loaded().then(function(){
console.log(friends);
angular.forEach($scope.participants, function(part){
var i = _.toString(part.facebook_id);
console.log(part.facebook_id);
var f = _.find(friends, {'id': i});
console.log("f value is: " + f);
if (f) {
console.log("Found matching facebook id: " + part.facebook_id);
removeItemsById(friends, part.facebook_id);
}
})
$scope.friends = friends;
})
function removeItemsById(arr, id) {
var i = arr.length;
if (i) { // (not 0)
while (--i) {
var cur = arr[i];
if (cur.id == id) {
arr.splice(i, 1);
}
}
}
}

How to display record information from my Firebase database?

I have in my database this node :
I have this select list
I would search events that its startdate matches the select item from the select list.
I try this code to show the evets that matches 'today' startdate:
//Switch label of selected item :
switch($scope.search.dateOption.label)
{
case 'Today':
{
var reff = new Firebase("https://event-application.firebaseio.com/event");
reff.orderByChild("startdate").startAt((new Date()).toISOString())
.on("child_added", function(snapshot) {
console.log(snapshot.key())
var a= snapshot.key() ;
reff.orderByChild("id").equalTo(a).on("child_added", function(snapshot) {
console.log(snapshot);
});
})
}
break;
}
'console.log(snapshot.key())' works well :
But when i try to display all the record information, nothing is displayed.
Can someone help me please.

Resources