Compare Value from Database using Node JS [duplicate] - javascript

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 1 year ago.
I have checked some links to compare two array but
I want to compare and check if the value which are present in database are similar to value which are present in fileName
Problem is fileName is not and Array and I am passing Value to it via For Each from another function so it can be any value
fileName= JavaScript
fileName= Java
fileName= NodeJs
fileName= ReactJs
fileName= Oops
but singleProduct is array that's why I used for loop to extract name from it.
code:
function checkDoc(data, childProduct, fileName, pathName, req, res) {
return new Promise((resolve, reject) => {
Document.findAll({
raw: true,
where: {
product_id: childProduct.id,
},
})
.then((productDoc) => {
productDoc.forEach((singleProduct) => {
if (singleProduct.name === fileName) {
//print matched value
} else {
//print unmatched value
}
});
})
.catch(function (err) {
return reject(
getFailureResponseJson("Can't be added please try again :) " + err)
);
});
});
}
value present inside singleProduct.name
Oops
Java
JavaScript
value present inside fileName
Oops
Java
JavaScript
NodeJs
ReactJs
Need Output like this
Matched Value:
Oops
Java
JavaScript
Unmatched Value:
NodeJs
ReactJs

You can try storing the values on to 2 arrays.
...
const matchedValues = [];
const unmatchedValues = [];
if (singleProduct.name === fileName) {
matchedValues.push(fileName)
} else {
unmatchedValues.push(fileName)
}
...
// Print

Related

Add every returned string into a text file [duplicate]

This question already has answers here:
How to append to a file in Node?
(18 answers)
Closed 1 year ago.
I have a program that returns the title of a youtube video when provided its id and it works fine. The issue is when I try to add the returned result to a text file it only adds the last string whereas when I console.log the result it prints the whole returned result. Where did I go wrong. How can I make it add the whole returned string into the text file. Any help is appreciated. Thanks in advance.
google.youtube('v3').videos.list({
key: youtubeKey,
part: 'snippet,contentDetails,statistics',
id: 'Ks-_Mh1QhMc,c0KYU2j0TM4,eIho2S0ZahI',
}).then((response) => {
const {
data
} = response;
data.items.forEach((item) => {
const title = (`${item.snippet.title}`)
console.log(title)//logs every result
fs.writeFileSync('filePath', title)//logs only the last string
})
}).catch((err) => console.log(err));
});
This is because you keep overwriting the file, so only the last string is in the file. You need to use appendFile, rather than writeFile, which overwrites the previous data.
google.youtube('v3').videos.list({
key: youtubeKey,
part: 'snippet,contentDetails,statistics',
id: 'Ks-_Mh1QhMc,c0KYU2j0TM4,eIho2S0ZahI',
}).then((response) => {
const {
data
} = response;
data.items.forEach((item) => {
const title = (`${item.snippet.title}`)
fs.appendFileSync('filePath', title)//logs all strings
})
}).catch((err) => console.log(err));
});

Can't store API data in js global variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Using async/await with a forEach loop
(33 answers)
Closed 1 year ago.
I am trying to build a simple crypto portfolio in nodejs by fetching prices from coingecko API. I set up a simple mongodb with all assets and I am parsing through the db and fetching each price. The fetch works as I can console.log the results however I cannot seem to be able to store the prices in a variable that I can call outside the fetch function. Thus, I cannot pass the prices to my ejs file. I am quite new to js (coming from python), and it seems that I am missing someting on how to handle api results, here is my code:
app.get('/dashboard', (req, res) => {
Holdings.find ((err, allHoldings) => {
if (err) {
res.type('html').status(500);
res.send('Error: ' + err);
}
else if (allHoldings.length == 0) {
res.type('html').status(200);
res.send('You have no holdings');
}
else {
var priceList = {};
allHoldings.forEach(async coin => {
coin = coin.asset;
const uri = 'https://api.coingecko.com/api/v3/simple/price?ids=' + coin + '&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&//include_24hr_change=false&//include_last_updated_at=false';
const fetch_price = await fetch(uri);
const json = await fetch_price.json()
const price = json[coin]['usd'];
priceList[coin] = price;
priceList.save;
console.log(priceList);
return priceList;
});
console.log(priceList);
res.render('dashboard', { holdings : allHoldings})
}
});
});
As you can see I set a priceList object before performing the API fetch and then I try to push the pair {coin : price} to that object. The first console.log works fine, however the second one only logs an empty object.
Any idea ?
Thanks

Change A Property For Every Dynamic Object In A Variable

I am storing JSON objects with a name and token value
Example Object in tokenHandler.json
{
"A Random Name":{
"token": 0
}
}
My Goal Is to have a function add + 1 to token for every object in the JSON File every 5 seconds
function addToken() {
const fs = require("fs");
const tokenHander = require("tokenHandler.json");
// My question is on this line of code
tokenHandler.token = tokenHandler.token + 1;
fs.writeFile("tokenHandler.json", JSON.stringify(tokenHandler), (error) => {
if (error) return console.log(error);
});
return console.log("Added Token!");
}
setInterval(addToken, 5000);
What im having trouble with is accessing every object inside tokenHandler. With the current line; a 2nd "token" property is added into the object instead of incrementing the original. I want to have a way to access and change every token property of every object present in the json file regardless of the name of the object
You can use the Object.values method to accomplish this. Object.values() will return an array of the values of object, which can then be chained using forEach to increase the value of token
function addToken() {
const fs = require('fs')
const tokenHander = require('tokenHandler.json')
Object.values(tokenHander).forEach(item => item.token++)
fs.writeFile('tokenHandler.json', JSON.stringify(tokenHandler), (error) => {
if (error) return console.log(error)
})
return console.log('Added Token!')
}
setInterval(addToken, 5000)

Why is the array variable not saved after the dbs call - node js [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I have a schema which saves Cat information. I then want to create an array of all the cat_urls, however when I call the array outside of the dbs call, the array is empty
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
})
console.log(cat_urls, 'here not working') // I want cat_urls to also be populated here
So Inside the Cat.find() call cat_urls has values like this:
[ 'www.hello.co.uk', 'www.testing.co.uk' ] 'here'
But outside cat_urls = []
I guess this is to do with the fact that node js does not run in a specific order, but how can I solve this issue?
I think it's working but your find function returns a promise that resolves asynchronously.
Try:
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
}).then(function(){
// Promise has completed, now this console log will trigger only after the cat's names are pushed.
console.log(cat_urls);
})

Implement bad word filter in to my input in html?

I plan on putting this list of bad words (https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/blob/master/en) into a .txt file on my web server. How can I this javascript check the variable "userNickName" against the .txt file named "blacklist.txt" on my web server.
(This is the code I want the bad word check implemented on, how would I do that?)
if (wsIsOpen() && null != userNickName) {
var msg = prepareData(1 + 2 * userNickName.length);
msg.setUint8(0, 0);
for (var i = 0; i < userNickName.length; ++i) msg.setUint16(1 + 2 * i, userNickName.charCodeAt(i), true);
wsSend(msg)
Make an JS array like badWords = ["boob","boobs","..."];
this could be done with Get file contents in java script and How do I split a string, breaking at a particular character?
Or directly with PHP on the server side.
$badWords = file_get_contents('https://raw.githubusercontent.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/master/en');
$badWords = explode("\n", $badWords);
echo 'badWords = ["'.implode('","', $badWords).'"];';
After that, How to find if an array contains a specific string in JavaScript/jQuery? (2nd answer for a not-JQuery one)
message.save((err) => {
if (err)
sendStatus(500)
Messages.findOne({ message: 'badword' }, (err, censored) => {
if (censored) {
console.log('cendsored words found', censored)
message.remove({ _id: censored.id }, (err) => {
console.log('removed censored message')
})
}
})
io.emit('message', req.body)
res.sendStatus(200);
})## Heading ##

Categories