Data that is not found is not triggering the function - javascript

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?

Related

How I email implement in query on my code

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

Sorting data based on time stored not working after getting deployed in node JS application

I developed a simple MERN stack application and for that one of the use case was that I wanted to sort my data based upon the time that I took from user (in my backend) and thus wrote the following code in my node.js backend for it:-
When the program execution comes to the condition where check1 and check2 both are present then when I am running the application on localhost (locally) then it is working correctly and giving desired output but when I deployed the application on heroku then that block of code is not giving the same/desired output for the same set of data.
With the exact same code why is this difference I am unable to figure out any solution/alternative way to this problem would be helpful.
const allDays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const getCurrentDay = () => {
let date = new Date();
let daynum = date.getDay();
return allDays[daynum];
}
const getCurrentHour = () => {
return parseInt(new Date().getHours())
}
const sortSubject = (a, b) => {
let day = getCurrentDay();
let check1 = a.routine.find((obj) => {
return obj.day === day;
})
let check2 = b.routine.find((obj) => {
return obj.day === day;
})
if (check1 && check2) {
const hours1 = check1.time.split(":")[0];
const hours1 = check2.time.split(":")[0];
const hrs1 = parseInt(hours1);
const hrs2 = parseInt(hours2);
const currHour = getCurrentHour();
if (Math.abs(hrs1 - currHour) > Math.abs(hrs2 - currHour)) {
return 1;
}
return -1;
} else if (check1) {
return -1;
}
return 1;
}
Here is the screenshot for reference:-
On localhost
Deployed Version
Edit
Here is the schema for my subject model:-
const subjectSchema = new mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:"user",
required:true
},
subName:{
type:String,
required:true
},
routine:{
type: [{day:String,time:String,link:String}]
}
});
Here is where I am calling the particular function when I fetched all the subjects of a user before sending it to the client I sort it
router.get(
"/getsubjects",
authorizeuser,
async(req,res)=>{
try{
//Find all the subjects of the logged in user
const subjects = await Subject.find({user:req.user.id});
subjects.sort(sortSubject);
return res.json({subjects});
}catch(err){
console.log(err);
res.status(500).json({error:"Some Internal Error Occured"});
}
}
)
Here is an sample subject:-

Invites command bot reply sending message multiple times

I am using the invite tracker from the WOK tutorials, and even though the code works perfectly fine, and im using a command handler that has 0 issues, for some reason, the bot replies with multiple messages instead of 1 as seen in this image:
Here is the code that I used for the invites command:
const Discord = require("discord.js")
module.exports = {
commands: 'invites',
callback: (message) => {
const { guild } = message
guild.fetchInvites().then((invites) => {
const inviteCounter = {}
invites.forEach((invite) => {
const { uses, inviter } = invite
const { username, discriminator } = inviter
const name = `${username}#${discriminator}`
inviteCounter[name] = (inviteCounter[name] || 0) + uses
})
let replyText = ''
const sortedInvites = Object.keys(inviteCounter).sort((a, b) => inviteCounter[b] - inviteCounter[a])
for (const invite of sortedInvites) {
const count = inviteCounter[invite]
replyText += `\n${invite} has invited ${count} member(s)!`
const embed = new Discord.MessageEmbed()
embed.setTitle('Invites: ')
embed.setDescription(replyText)
message.reply(embed)
}
})
}
}
Fyi last time i posted this i forgot to post the code so yeah that was dumb my bad.
This is because you have message.reply in a for...of loop.
for (const invite of sortedInvites) {
const count = inviteCounter[invite]
replyText += `\n${invite} has invited ${count} member(s)!`
const embed = new Discord.MessageEmbed()
embed.setTitle('Invites: ')
embed.setDescription(replyText)
message.reply(embed) //here
}
You probably meant to put it outside of the loop so that it sends the resulting embed after all the iterations.

Firebase Cloud Function updating ref with incorrect values

I want to add a new node to the database if the node doesn't exist. I don't want to return anything to the client, I just want to update the database with the new values. On the client I have a listener that observes the credit_counts property, once the update happens it receives it there and notifies all users that this particular user has a new credit.
In the code below I check to see if (!snapshot.exists() and if it's not there I add the node to the database using admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict });. After pasting the url I check the db and the layout is:
I'm a Swift developer. In Swift I can just do:
Database.database().reference().child("/user_credits/\(creditId)/\(userId)").setValue(dict) and the tree will be correct.
user_credits > {creditId} > {userId} > dict are incorrect. It should be user_credits > sample_123 > user_xyz > dict values. Where am I going wrong at?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateViewsCtAtPostsRef = functions.https.onRequest((request, response) => {
const currentTimeStamp = Date.now();
const receivedTimeStamp = admin.database.ServerValue.TIMESTAMP;
const creditId = "sample_123";
const userId = "userId_xyz";
admin.database().ref('user_credits').child(creditId).child(userId).once('value', snapshot => {
if (!snapshot.exists()) {
var dict = {
"joined_date": receivedTimeStamp,
"timeStamp": receivedTimeStamp,
"credits_count": 1
};
return admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict });
} else {
const previousTimeStamp = snapshot.child("timeStamp").val();
const creditsCount = snapshot.child("credits_count").val();
if (previousTimeStamp + whatever) < currentTimeStamp {
let updatedCount = creditsCount + 1
return admin.database().ref('/user_credits/{creditId}/{userId}').update({ "timeStamp": receivedTimeStamp, "credits_count": updatedCount });
} else {
return true
}
}
});
});
I had to change the ref to:
return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 });
I also had to update the ref inside the else statement to follow the same format.
The syntax is fine, but the reference does not match the structure; that should rather be:
admin.database().ref('user_credits').child(creditId).child(userId).child('dict')
... else there won't be any snapshot.child("timeStamp") or snapshot.child("credits_count").

Unable to get metamask balance and send amount through metamask extension using javascript(web3)

I've integrated metamask on my site, but I need to send amount and also check the balance on ERC 20 token using metamask but nothing works for me.I try different coding and methods on WEB3.
Kindly provide the executed code to me.
But using below code I'm unable to get any details relate ERC20 tokens , but for me ,ETH is working fine.
Here is my code:
var contractadd = "0xd26114cd6ee289accf82350c8d8487fedb8a0c07";
$.getJSON( "https://api.etherscan.io/api?module=contract&action=getabi&address="+contractadd, function( data ) {
var abivalue = (data.result);
if (typeof web3 !== "undefined") {
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
alert("Metamask extension not added on your browser");return false;
}
const contract_address = contractadd;
var userAddress = '0x12A922212C20EFe9b8d5799CC67C619F9F1617b9';
var amount = 0.2;
web3.eth.getBlock('latest',function(err,getBlock) {
web3.eth.getGasPrice(function(err, getGasPrice) {
web3.eth.getAccounts(function(err, accounts){
if (err != null) {
console.log(err)
}
else if (accounts.length === 0) {
alert("Your metamask account is locked please unlock");return false;
}
else {
var contractAddress = contractadd;
var FromAddress = accounts[0];
var ToAddress = "hghfghfg";
var Amount = 0.5;
var Key = "";
var Amount=Amount*1000000000000000000;
const abi =JSON.parse(abivalue);
let contract = web3.eth.contract(abi).at(contractAddress);
contract.balanceOf(FromAddress, (error, balance) => {
contract.decimals((error, decimals) => {
alert(balance);
console.log(balance.toString());
});
});
}
});
});
})
});
You must pass arguments like this:
contract.balanceOf(address,{},function (err, transactionHash){
console.log(transactionHash);
window.alert(transactionHash)
});
you have missed empty {} in your code.

Categories

Resources