How I email implement in query on my code - javascript

This is a MongoDB API I create '/inventoryItems' this API already shows for all Inventory items
This is my back-end database FORM data
{ _id:2749d97592b4b1d084e20a2
supplierName:"carsale"
email:"imd572258#gmail.com"
brand:"audi"
quantity:"1"
price:"520"
description:"car want need want "
img:"https://res.cloudinary.com/dk0lorahh/image/upload/v1648239069/
}
How i do use const email = req.query.eamil
const query={email :email}
app.get("/inventoryItems", async (req, res) => {
const page= parseInt(req.query.page);
const size = parseInt(req.query.size);
**const email = req.query.email**
const query = {};
const cursor = inventoryItemsCollection.find(query);
let inventoryItems ;
if( page || size ){
inventoryItems = await cursor.skip(page*size).limit(size).toArray();
}else{
inventoryItems = await cursor.toArray();
}
res.send(inventoryItems);
});
**if i do like this**
const page= parseInt(req.query.page);
const size = parseInt(req.query.size);
const email = req.query.email
**const query = {email: email};**
const cursor = inventoryItemsCollection.find(query);
let inventoryItems ;
if( page || size ){
inventoryItems = await cursor.skip(page*size).limit(size).toArray();
}else{
inventoryItems = await cursor.toArray();
}
res.send(inventoryItems);
});
it's working find the email result but When mY Form data are not working not showing
showing empty
[]
I want a way how to do both works email results and my form results showing

Related

Execute promise or await with generated string variable

I am building a mongoose query and storing it in a variable call query. The code below shows it
let query = "Product.find(match)";
if (requestObject.query.sortBy) {
query = query.concat(".", "sort(sort)");
const parts = requestObject.query.sortBy.split(":");
sort[parts[0]] = parts[1] === "desc" ? -1 : 1;
}
if (requestObject.query.fields) {
query = query.concat(".", "select(fields)");
const fields = requestObject.query.fields.split(",").join(" ");
const items = await Product.find(match).sort(sort).select(fields); //.populate("category").exec();
/**const items = await Product.find(match).sort(sort).select("-__v"); //.populate("category").exec();**/
}
I am facing an issue when attempting to run a mongoose query that I have generated and stored in a string. When I run it in post man, the response is 200 but no data is returned. Below is a console.log(query) on line 2
what I hope to achieve is to have await or create a new promise execute the content id query variable like shown below
const items = new Promise((resolve) => resolve(query)); //.populate("category").exec();
items
? responseObject.status(200).json(items)
: responseObject
.status(400)
.json({ message: "Could not find products, please try again" });
I will appreciate it very much that and also if you can give me a better way of doing it, I will love that
This doesn't really make sense. You are building a string, not a query. You can't do anything with that string. (You could eval it, but you really shouldn't). Instead, build a query object!
let query = Product.find(match);
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {};
sort[field] = dir === "desc" ? -1 : 1;
query = query.sort(sort);
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
}
//query.populate("category")
const items = await query.exec();
if (items) {
responseObject.status(200).json(items)
} else {
responseObject.status(400).json({ message: "Could not find products, please try again" });
}
If you really want to get that string for something (e.g. debugging), build it separately from the query:
let query = Product.find(match);
let queryStr = 'Product.find(match)';
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {[field]: dir === "desc" ? -1 : 1};
query = query.sort(sort);
queryStr += `.sort(${JSON.stringify(sort)})`;
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
queryStr += `.select(${JSON.stringify(fields)})`;
}
//query.populate("category")
//queryStr += `.populate("category")`;
console.log(queryStr);
const items = await query.exec();
…

Creating a covid-19 app and im getting issues with the API being dynamic

Im working on a Coronavirus application. And im using this API: https://api.covid19api.com/live/country/south-africa
In my application a user is supposed to type the name of any given country and it should display the numbers of deaths, confirmed cases, recovered people. I keep getting a 404 error.
HTML & CSS can be found here:
https://github.com/Kazim786/coronavirus-updates/blob/master/index.html
https://github.com/Kazim786/coronavirus-updates/blob/master/style.css
(havent done much styling yet)
Here is my Javascript code:
// The api: https://api.covid19api.com/live/country/south-africa
// const theCountries = await axios.get(`https://api.covid19api.com/live/country/south-africa`)
// console.log(theCountries.data[0].Confirmed)
// console.log(theCountries.data[0].Deaths)
// console.log(theCountries.data[0].Recovered)
const countries = document.getElementById('countries').value
const results = document.getElementsByClassName('results')
const submitBtn = document.getElementById('submit')
const data = []
console.log(countries)
//Async Function
//`https://api.covid19api.com/live/country/${countries}`
console.log(byCountries())
async function byCountries(){
try {
const theCountries = await axios.get(`https://api.covid19api.com/live/country/${countries}`)
const deaths = theCountries.data[0].Deaths
const confirmed = theCountries.data[0].Confirmed
const recovered = theCountries.data[0].Recovered
data.push(deaths, confirmed, recovered)
console.log(theCountries)
await console.log(data)
}
catch{
console.log("Error");
}
}
//Show results function:
function showResults(){
if (countries !== null){
results.innerHTML = `${countries} has number of deaths, confirmed cases, recovery as the following: ${data}. `
} else {
results.innerHTML = 'Enter a name of a Valid Country'
}
}
//Add Event Listener
submitBtn.addEventListener('click', showResults)
You're trying to get the result while the input field is empty as js loads.
You can make the submit button call both byCountries() and showResults(), and you'll also need to fetch the value inside byCountries()
submitBtn.addEventListener('click', () => {
byCountries()
showResults()
})
async function byCountries(){
try {
const countries = document.getElementById('countries').value
const theCountries = await axios.get(`https://api.covid19api.com/live/country/${countries}`)
...

Puppeteer blocking variables inside functions

I recently made a quick web scraper using puppeteer as it targets a JS website and want it to send the output that i get inside my console into discord. The thing is that I always get e.g price not defined or so when the script tries to send the web hook onto discord. Thank you all for your help in advance here is my code if someone can help me out please. I mean where should I put my const embed in order for it to work properly.
const puppeteer = require('puppeteer-extra');
// add stealth plugin and use defaults (all evasion techniques)
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const { Webhook, MessageBuilder } = require('discord-webhook-node');
const hook = new Webhook("https://discordapp.com/api/webhooks/733332015654371361/9VGAVW-BNlf3G4j3L6GhAIDni17yNIVf9gfmf_TNTQafP40LqYvRwhaYZzL_b58kpkkl");
const url = "https://www.asos.com/fr/nike/nike-air-max-270-baskets-triple-noir-ah8050-005/prd/12490103?clr=noir-triple&colourwayid=16391201&SearchQuery=nike air max 270";
puppeteer.use(StealthPlugin());
async function ConfigureBrowser(){
const browser = await puppeteer.launch({ headless: true }); // for test disable the headlels mode,
const page = await browser.newPage();
await page.setViewport({ width: 1000, height: 926 });
await page.goto(url,{waitUntil: 'networkidle2'})
return page;
};
async function Scrape(page) {
// await page.reload();
console.log("start evaluate javascript")
/** #type {string[]} */
var productINFO = await page.evaluate(()=>{
var div = document.querySelectorAll('.core-product-container');
console.log(div) // console.log inside evaluate, will show on browser console not on node console
const productnames = []
div.forEach(element => {
var titleelem = element.querySelector('#aside-content > div.product-hero > h1');
if(titleelem != null){
productnames.push(titleelem.textContent.trim());
} //#aside-content > div.product-hero > h1
});
const productprice = []
div.forEach(element => {
var price = element.querySelector('[class="current-price"]');
if(price != null){
productprice.push(price.textContent.trim());
}
});
const productsizes = []
div.forEach(element => {
var sizes = element.querySelector('[data-id="sizeSelect"]');
if(sizes != null){
productsizes.push(sizes.textContent.trim());
}
// productsizes.forEach()
})
return [productnames, productprice, productsizes]
})
return productINFO;
// const embed = new MessageBuilder()
// .setTitle(productnames)
// .setURL(url)
// .addField('Prix', productprice, true)
// .addField('sizes', productsizes, true)
// .setColor(8008905)
// // .setThumbnail({image})
// .setDescription('Checked')
// //.setImage(image)
// .setFooter('', 'https://cdn.discordapp.com/attachments/720763827658162260/730786942316183603/image0.jpg')
// hook.send(embed);
discoord(productINFO);
console.log(productINFO);
//browser.close()
} ;
async function Monitor() {
let page = await ConfigureBrowser();
await Scrape(page);
// console.log(productINFO);
}
Monitor();

Data that is not found is not triggering the function

const Discord = require("discord.js");
const mongoose = require("mongoose");
const roblox = require("noblox.js");
const RobloxDB = require("../models/roblox.js");
const ModLogDB = require("../models/modlog.js");
ModLogDB.find({
offenderID:ID
},(err,data)=>{
if(err) console.log(err);
if(data){
var TotalActions = 0
data.forEach(Act=>{
if(TotalActions >= 5){
return;
}
TotalActions = TotalActions + 1
message.channel.send("**Sanction Type:** ${Act.sanctionType} | **Sanction ID:** ${Act.sanctionID} - **Sanction Reason:** ${Act.sanctionReason}")
})
}
if(!data){
message.channel.send("**History Clear** - There are no records for that user!")
return;
}
})
The part of the code where if(!data) the message is not sending.
I have logged from where it says console.log and have also logged the data not found area and have found that the no data found side is not printing, why might this be?

Get author user ID using Parse.Query not current user

I have two parse classes, User and Place.
If user ads a place, user is added as Pointer to the Place user column.
In order to list all places and determine how many places has a user, i use the following query:
loadTotalPointsDetail(params: any = {}): Promise<Place[]> {
const page = params.page || 0;
const limit = params.limit || 100;
const query = new Parse.Query(Place);
query.equalTo('user', Parse.User.current());
query.skip(page * limit);
query.limit(limit);
query.include('category');
query.include('user');
query.doesNotExist('deletedAt');
return query.find();
}
Filtering by Parse.User.current()) i will get current user places.
If i don't filter by Parse.User.current()) it will return all places as objects, containing all data.
How can i filter by place real author / user? not current (loggedIn)?
loadTotalPointsDetail(params: any = {}): Promise<Place[]> {
const page = params.page || 0;
const limit = params.limit || 100;
const query = new Parse.Query(Place);
const user = new Parse.User();
user.id = 'The id of the user that you want to search for';
query.equalTo('user', user);
query.skip(page * limit);
query.limit(limit);
query.include('category');
query.include('user');
query.doesNotExist('deletedAt');
return query.find();
}
I'll post the solution here, not the most indicated but it works for me:
async loadData() {
try {
const places = await this.placeService.loadTotalPointsDetail(this.params);
const placeU = await this.placeService.loadPlaceU(this.getParams().id);
for (const place of places) {
this.places.push(place);
}
let u = placeU.user.id;
let totalUserPlaces = places.filter(x => x.user.id == u);
if (totalUserPlaces) {
/* The total returned by reduce() will be stored in myTotal */
const myTotal = totalUserPlaces.reduce((total, place) => {
/* For each place iterated, access the points field of the
current place being iterated and add that to the current
running total */
return total + place.points;
}, 0); /* Total is initally zero */
this.points = myTotal;
} else {}
} catch (err) {
const message = await this.getTrans('ERROR_NETWORK');
this.showToast(message);}}
so i'm loading two separate queries:
const places = await this.placeService.loadTotalPointsDetail(this.params); -> Gets all posts listings
const placeU = await this.placeService.loadPlaceU(this.getParams().id); --> Gets the ID for current post
I extract the user post ID:
let u = placeU.user.id;
I filter using that user in order to get his posts:
let totalUserPlaces = places.filter(x => x.user.id == u);

Categories

Resources