Good afternoon, I am trying to change the remainder of the product in mongoose in a loop. But persistence doesn't work. I would be grateful for your help!
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
if (orderItems?.length > 0) {
orderItems.forEach(async orderItem => {
if (orderItem.varIdx === 0 && product.stock !== null) {
const stockResult = product.stock - orderItem.count
product.stock = stockResult
if (stockResult === 0) product.status = statusOutOfStock._id
} else {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
product.variations[orderItem.varIdx].stock = stockResult
if (stockResult === 0)
product.variations[orderItem.varIdx].status = statusOutOfStock
}
})
await product.save()
}
}
I was able to solve this problem.
/* Deduction of stock */
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
/* Get order items by productID */
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
/* If order items exists */
if (orderItems?.length > 0) {
/* Run of order items and write new stock */
const proDb = await Product.findById(product._id)
let buffer = []
await Promise.all(
orderItems.map(async orderItem => {
if (orderItem.varIdx === 0 && product?.stock !== null) {
const stockResult = product.stock - orderItem.count
proDb.stock = stockResult < 0 ? 0 : stockResult
if (stockResult === 0) proDb.status = statusOutOfStock._id
} else if (
!!product?.variations[orderItem.varIdx]?.stock !== null &&
orderItem.varIdx !== 0
) {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
if (buffer?.length === 0) buffer = [...product.variations]
buffer[orderItem.varIdx].stock =
stockResult < 0 ? 0 : stockResult
proDb.variations = buffer
if (stockResult === 0)
proDb.variations[orderItem.varIdx].status = statusOutOfStock
}
})
)
await proDb.save()
}
}
Related
FilterCriterias: any = []
public productChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'productType') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if (elem.filterValueList?.length == 0 && elem.filtercolumnName == 'productType') {
// const idy = elem.filtercolumnName.indexOf('productType')
// if (idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'productType') {
console.log(true);
const idy = element.filtercolumnName.indexOf('productType')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
public collectionChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'collections') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if(elem.filterValueList?.length == 0) {
// const idy = elem.filtercolumnName.indexOf('collections')
// console.log('collectoinindex',idy);
// if(idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'collections') {
console.log(true);
const idy = element.filtercolumnName.indexOf('collections')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
I am having two functions in which I want to generate a format like below
FilterCriterias: [
{
filtercolumnName:`producttype`,
filterValueList: [`hat`, 'cup']
},
{
filtercolumnName: "collections",
filterValueList: [`modern`, 'pant']
},
]
if the filterValueList.length == 0 means i want to remove the entire object which hold the filerValueList.length == 0.
For Example, if filterValueList of collections is empty means only the producttype needs to be there in the array.
You can achieve that using Array.filter function, like the following:
this.FilterCriterias = this.FilterCriterias.filter(
(item) => !!item.filterValueList.length
);
I am guessing this should do the job if I understood correctly what you want to do. This will loop through all objects of the array, check if their filterValueList array is empty and if so, it will remove them from the array:
let i = 0;
while (i < FilterCriterias.length) {
if(FilterCriterias[i].filterValueList.length == 0) {
FilterCriterias.splice(i, 1);
} else {
i++;
}
}
I'm trying to import Wordpress categories from .cvs file. I'm writing a simple app in react and I've got a function:
componentDidUpdate( prevProps, prevState ) {
let that = this
if (prevState.syncStatus !== this.state.syncStatus && this.state.syncStatus == 'posts') {
row_terms.forEach( (element, inx) => {
let parent = that.state.parent_id;
let _terms = element.split('>')
_terms = _terms.map(function(e){return e.trim();});
const total = _terms.length
_terms.forEach( (_term, index) => {
addCategory(_term, that.state.parent_id).then(result => {
let term_id
if( result.code && result.code == 'term_exists' ) {
term_id = result.data.resource_id
} else {
term_id = result.id
}
if ( ( 1 + index ) === total ) {
categories.push(term_id)
} else {
that.setState({parent_id: term_id})
}
})
})
})
}
}
and addCategory:
import WooCommerce from './woocommerce'
async function addCategory(name, parent) {
console.log('parent', parent)
try {
return await WooCommerce.postAsync('products/categories', {name: name, parent: parent}).then(result => {
return JSON.parse(result.toJSON().body);
});
} catch (e) {
return e
}
}
export default addCategory
and initial value is set
constructor(props) {
super()
this.state = {
parent_id: 0,
}
}
I want to add cateogories one after another because I need to set parent_id for categories that are children. So when it adds a category and the condition
if ( ( 1 + index ) === total ) {
is not met I want to set parent_id and then use it in next iteration. But it doesn't work.
When I use
console.log(that.state.parent_id)
after
that.setState({parent_id: term_id})
It prints correct value.
When i run my app it prints 0 ( console.log in addCategory() ) for all categories before any request is made.
.forEach() isn't aware of the asynchronicity of addCategory; you'll either have to chain all of those thens, or preferably just use async/await and plain old for loops, which can be used with await without extra hoops to jump through.
Assuming you want to loop through all of the row_terms and process them, you'll also need to await on those promises...
const categories = [];
const promises = row_terms.map(async (element) => {
const terms = element.split(">").map((e) => e.trim());
const total = terms.length;
let parent = null;
for (let i = 0; i < total; i++) {
const term = terms[i];
const result = await addCategory(term, parent);
const term_id = result.code && result.code === "term_exists" ? result.data.resource_id : result.id;
if (i === total - 1) {
categories.push(term_id);
} else {
parent = term_id;
}
}
});
await Promise.all(promises);
I got this firestore query for filtering data from my database but my min max is not filtering out my max price. I don't understand why.
The else function is not working
but when I test the query in the else if statements then the min max is working without problems.
My body of the GET request:
{
"pageNumber": 1,
"seller": "",
"name": "shirt",
"category": "Shirts",
"min": 0,
"max": 120,
"rating": [ 3, 4 ],
"order": "lowest"
}
My code:
const { admin, db } = require("../util/admin");
const config = require("../util/config");
const firebase = require("firebase");
const { data } = require("../data");
//get all products
let latestDoc = null;
exports.getAllProducts = (req, res) => {
const limit = 4;
const page = Number(req.body.pageNumber) || 1;
const name = req.body.name || "";
const category = req.body.category || "";
const order = req.body.order || "";
const min =
req.body.min && Number(req.body.min) !== 0 ? Number(req.body.min) : 0;
const max =
req.body.max && Number(req.body.max) !== 0 ? Number(req.body.max) : 1000000;
const rating = req.body.rating[0];
const sortOrder =
order === "lowest" ? "asc" : order === "highest" ? "desc" : "asc";
const orderType =
order === "newest"
? "createdAt"
: order === "toprated"
? "rating"
: "price";
console.log(min);
console.log(max);
if (category === "" && rating === 0 && name === "") {
console.log("geen filter");
db.collection("products")
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (category === "" && rating > 0 && name === "") {
console.log("products");
db.collection("products")
.where("rating", ">=", rating)
.orderBy("rating")
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (category !== "" && rating === 0 && name === "") {
console.log("category");
db.collection("products")
.where("category", "==", category)
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (name !== "" && category === "" && rating === 0) {
console.log("naam");
db.collection("products")
.where("searchName", "array-contains", name)
.orderBy("price")
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else {
console.log("else");
db.collection("products")
.where("searchName", "array-contains", name)
.where("rating", ">=", rating)
.orderBy("rating")
.where("category", "==", category)
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
}
};
There are a few problems with your query:
You have a orderBy() between 2 query filters, this is not allowed, so you have to move .orderBy("rating") to after .where("category", "==", category);
You have both a startAfter() and a startAt() clause in your query, you can't do that, you either start after a certain value or at a fixed position;
So say you would change your query to something like this:
db.collection("products")
.where("searchName", "array-contains", name)
.where("category", "==", category)
.where("rating", ">=", rating)
.orderBy("rating")
.orderBy(orderType, sortOrder)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
It should work.
I am working on a project of Amazon Alexa of booking a table in a restaurant and I have four intents:
makeReservation
futureOrCurrentLocation
getRestaurantName
selectRestaurants
I am facing one issue that the linear flow of intent is not working. I have stored the previous intent in the session and checked the previous intent from the session and on that basic I am calling the next intent.
But when I say Alexa with the previous intent String in the response of the current intent, it jumps to the new intent we have called, but it throws an exception.
Actually it should work like if I say some intent String in the response of other intent then it should repeat the current intent once again.
And one more issue I am facing is that I need to append the String in the user utterance like e.g.:
Alexa: "Where would you like to go?"
User: "Go to {Restaurant Name}"
I didn't want to append this "Go to" in the restaurant name.
// Lambda Function code for Alexa.
const Alexa = require("ask-sdk");
// Book a table
const makeReservation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'makeReservation' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.tableTalkType = 1;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
return responseBuilder
.addDelegateDirective({
name: 'futureOrCurrentLocation',
confirmationStatus: 'NONE',
slots: {}
})
.withShouldEndSession(false)
.getResponse();
},
};
const futureOrCurrentLocation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'futureOrCurrentLocation' ;
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'makeReservation') {
const request = handlerInput.requestEnvelope.request;
// const responseBuilder = handlerInput.responseBuilder;
const slotValues = getSlotValues(request.intent.slots);
const location = slotValues.locationType.heardAs;
const tableTalkType = sessionAttributes.tableTalkType;
let say = '';
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
if (location == 'future location') {
say = `Future location not available at this moment. Please ask to current location.`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
} else if(location == 'current location' && tableTalkType == 1){
return responseBuilder
.addDelegateDirective({
name: 'getRestaurantName',
confirmationStatus: 'NONE',
slots: {}
})
.getResponse();
} else if (location == 'current location' && tableTalkType == 2) {
return userCreatedTableListing_Handler.handle(handlerInput);
} else {
say = `invalid input.Please try again`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const getRestaurantName_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'getRestaurantName' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'futureOrCurrentLocation') {
const request = handlerInput.requestEnvelope.request;
let slotValues = getSlotValues(request.intent.slots);
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
// SLOT: restaurantname
if (request.dialogState && request.dialogState == 'COMPLETED' && slotValues.restaurantname.heardAs) {
return new Promise((resolve) => {
getRestaurants(slotValues, handlerInput).then(say => {
resolve(handlerInput.responseBuilder.speak(say).reprompt(say).withShouldEndSession(false).getResponse());
}).catch(error => {
console.log(error);
});
});
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
}
};
const selectRestaurants_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'selectRestaurants' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'getRestaurantName') {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let slotValues = getSlotValues(request.intent.slots);
let say = '';
let restaurantListArray = sessionAttributes.sessionrestaurantList ? sessionAttributes.sessionrestaurantList : [];
sessionAttributes.previousIntent = '';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
let restaurantIndex = slotValues.selectRestaurant.heardAs;
let restaurantData = {
name: '',
address: '',
restaurantlatitude: '',
restaurantlongitude: '',
restaurantID:'',
restaurantImageUrl: '',
date: '',
time:'',
people: '',
};
if (restaurantListArray.length >= restaurantIndex) {
let jsonData = JSON.parse(restaurantListArray[restaurantIndex - 1]);
if ((restaurantIndex) && (jsonData[restaurantIndex].name !== '' && typeof jsonData[restaurantIndex].name !== undefined && jsonData[restaurantIndex].name !== null)) {
let restaurantAddress1 = jsonData[restaurantIndex].location.address1 ? jsonData[restaurantIndex].location.address1: '';
let restaurantAddress2 = jsonData[restaurantIndex].location.address2 ? jsonData[restaurantIndex].location.address2: '';
let restaurantAddress3 = jsonData[restaurantIndex].location.address3 ? jsonData[restaurantIndex].location.address3: '';
restaurantData['name'] = jsonData[restaurantIndex].name;
restaurantData['address'] = restaurantAddress1.concat(restaurantAddress2, restaurantAddress3);
restaurantData['restaurantID'] = jsonData[restaurantIndex].id;
restaurantData['restaurantImageUrl'] = jsonData[restaurantIndex].image_url;
restaurantData['restaurantlatitude'] = jsonData[restaurantIndex].coordinates.latitude;
restaurantData['restaurantlongitude'] = jsonData[restaurantIndex].coordinates.longitude;
sessionAttributes.restaurantData = restaurantData;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
say = `selected Restaurant name is ${jsonData[restaurantIndex].name} in ${restaurantAddress1} ${restaurantAddress2} ${restaurantAddress3}.`;
return responseBuilder
.addDelegateDirective({
name: 'bookingDate',
confirmationStatus: 'NONE',
slots: {}
})
.speak(say)
// .reprompt('try again, Please provide date')
.withShouldEndSession(false)
.getResponse();
} else {
say = 'Restaurant not available. please say again';
return responseBuilder
.speak(say)
.reprompt('Restaurant not available. please say again')
.withShouldEndSession(false)
.getResponse();
}
} else {
say = 'Please select valid input.';
return responseBuilder
.speak(say)
.reprompt('Please select valid input')
.withShouldEndSession(false)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const errorIntent_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'errorIntent' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let say = 'Sorry. There is some problem with the response. Please say again';
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
},
};
I am trying to filter an array of data like so:
let data =
[
{
"approval": "TPED",
"manufacturer": "Chesterfield"
},
{
"approval": "BV",
"manufacturer": "Faber"
}
]
let approvalVariable = "TP"
let filteredData = data.filter(x => x.approval.includes(approvalVariable))
console.log(filteredData)
So if approvalVariable is "TP", I want the new array to be:
[
{
"approval": "TPED",
"manufacturer": "Chesterfield"
},
]
I have it working when I do:
let filteredData = data.filter(x => x.approval == approvalVariable)
But when I try:
x.approval.includes(approvalVariable)
I get an error that x.approval.includes is not an object
I had it working at one point with .includes() but something is going wrong now.
Any help would be greatly appreciated.
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
var fireBaseResponse = firebase.database().ref();
fireBaseResponse.once('value').then(snapshot => {
let data1 = [];
let approval = this.props.navigation.state.params.approval
let comments = this.props.navigation.state.params.comments
let designStandard = this.props.navigation.state.params.designStandard
let diameter = this.props.navigation.state.params.diameter
let h2Compatible = this.props.navigation.state.params.h2compatible
let inletThread = this.props.navigation.state.params.inletThread
let manufacturer = this.props.navigation.state.params.manufacturer
let specificationNumber = this.props.navigation.state.params.specificationNumber
let testPressure = this.props.navigation.state.params.testPressure
let waterCapacity = this.props.navigation.state.params.waterCapacity
let workingPressure = this.props.navigation.state.params.workingPressure
snapshot.forEach(item =>{
const temp = item.val();
data1.push(temp);
return false;
});
////////Filter Method/////////
if(approval == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.approval.includes(approval))
}
if(waterCapacity == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.waterCapacity == waterCapacity)
}
if(designStandard== '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.designStandard == designStandard)
}
if(diameter == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.diameter == diameter)
}
if(inletThread == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.inletThread == inletThread)
}
if(workingPressure == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.workingPressure == workingPressure)
}
if(comments == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.comments == comments)
}
if(manufacturer == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.manufacturer == manufacturer)
}
if(testPressure == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.testPressure == testPressure)
}
if(specificationNumber == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.specificationNumber == specificationNumber)
}
if(h2Compatible == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.h2Compatible == h2Compatible)
}
/////////////////////Filter Method//////////////////
this.setState({data: data1});
});
}
render(){
var {navigate} = this.props.navigation;
let {params} = this.props.navigation.state;
return(
<ViewContainer>
<ScrollView>
<FlatList
data = {this.state.data}
keyExtractor = {(x, i) => i}
renderItem ={({item}) =>
<Text style = {styles.itemText}>
Approval: {item.approval} | Manufacturer: {item.manufacturer} | Specification Number: {item.specificationNumber} |
H2 Compatible: {item.h2Compatible} | Diameter: {item.diameter} | Water Capacity: {item.waterCapacity} |
Inlet Thread: {item.inletThread}{"\n"}
</Text>
}
/>
</ScrollView>
<View style ={styles.footer}>
<TouchableOpacity style ={styles.footerButton} onPress = { () => navigate("ValveSearchScreen")}>
<Text style ={styles.footerButtonText}>SEARCH</Text>
</TouchableOpacity>
</View>
</ViewContainer>
)
}
}
The problem was that it was searching for a property within the array object called includes. Obviously it could not find it so it was giving me the warning that the property did not exist. To fix this I changed the line to
let filteredData = data.filter(x => String(x.approval).includes(approvalVariable));
I hope this helps somebody else out in the future and you don't spend a week trying the figure it out with no help like I did.