Update inventory after purchase - javascript-objects

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\":\"סט קדושת יצחק\"}"

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)]

How to fetch unique id to delete the data in React Native Firebase

I am using Firebase to store my data. Now i want to delete the data under Shops Section but i am not understanding that how to fetch the Unique id to delete the data here is the screen shot.
Shops
4azTPmwIpbY9vfwf9CxKMMK74kI2
-LuTY5RZLYFqeY5iPjfR
-LxMsiVGtW5xgw4XsKQi
description: "demo"
image_url_banner: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Q..."
image_url_logo: "iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAIAAAC8ggxVAAA..."
name: "demo"
tagline: "demo shop here"
Here is my code i am not able to get id of any shop
deleteItem=()=>{
let shopRef = firebase.database().ref('Shops/' + firebase.auth().currentUser.uid);
let shopId = shopRef.key;
Alert.alert("id" , shopId)
var updates = {};
updates["/Shops/" + firebase.auth().currentUser.uid + shopId] = null;
return firebase
.database()
.ref()
.update(updates);
}
please suggest some code
You need to do the following:
let shopRef = firebase.database().ref('Shops/' + firebase.auth().currentUser.uid);
shopRef.on("value",(snapshot) => {
snapshot.forEach((childSnapshot) => {
var id = childSnapshot.key;
firebase.database().ref('Shops/' + firebase.auth().currentUser.uid).child(id).remove();
});
});
First attach a listener, then iterate inside the key and retrieve it using the key property.
Check here for more information:
https://firebase.google.com/docs/database/web/read-and-write

Http Post Json - Array

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
}

Is it possible to search for all keys that start with a certain prefix in Aerospike?

So I am looking to model our existing redis data into aerospike. One requirement that we have is to be able to get all the keys for a given user. For eg., say we have keys such as <id>:<timestamp>. Now, at some point in time, I need to get all keys for the given id, where I would require something like a prefix search across all keys in the aerospike namespace (which are indexed) to get the values for all <id>:<timestamp> keys. Would like to know if this is possible, and if yes, how.
You cannot do a query on key prefix directly. The server only stores the key digest, so the key value (<id>:<timestamp> in your case) doesn't get indexed.
The way to model this would be to add the <id> part of your key as a separate record bin. Then you can index that bin and run a query on it.
Here is a simple example - it's using the Aerospike Node.js client but the concept is the same no matter what client you prefer:
const Aerospike = require('aerospike')
const ns = 'test'
const set = 'demo'
// connect to cluster and create index on 'id' bin
var client = Aerospike.client()
client.connect((err) => {
assertOk(err, 'connecting to cluster')
createIndex('id', 'id_idx', Aerospike.indexDataType.STRING, () => {
// create a new sample record
var userId = 'user1'
var ts = new Date().getTime()
var key = new Aerospike.Key(ns, set, `${userId}:${ts}`)
var record = { id: userId, value: Math.random() }
client.put(key, record, (err) => {
assertOk(err, 'write record')
// query for records with matching 'id'
var query = client.query(ns, set)
query.where(Aerospike.filter.equal('id', userId))
var stream = query.foreach()
stream.on('error', (error) => assertOk(error, 'executing query'))
stream.on('end', () => client.close())
stream.on('data', (record, meta, key) => {
console.log(record)
})
})
})
})
function assertOk (err, message) {
if (err) {
console.error('ERROR: %s - %s', message, err)
process.quit()
}
}
function createIndex (bin, name, datatype, callback) {
var index = {
ns: ns,
set: set,
bin: bin,
index: name,
datatype: datatype
}
client.createIndex(index, (err, job) => {
assertOk(err, 'creating index')
job.waitUntilDone(100, (err) => {
assertOk(err, 'creating index')
callback()
})
})
}
Hope this helps!

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