Mongo DB SORTING data nodejs - node.js

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);
};

Related

Writing a database seeder class to seed multiple collections. (NodeJS, MongoDB)

Hi all I have been struggling all day with this and I was hopingsomeone might be able to assist me on figuring out the functionality. I'm still very new to asynchronous programming so any advice would be highly appreciated! I wrote two seeder classes which work great independently, and am opting to create a databaseSeeder class that I can use to run all my migrations from one file.
The issue I'm facing is that I need the UserSeeder to complete first because the ProductSeeder uses the ID's from the User model to link products to users. Please find my code for a reference:
User Seeder:
const mongoose = require("mongoose");
const User = require("../models/User");
const dotenv = require("dotenv");
const { faker } = require("#faker-js/faker");
const { v4: uuidv4 } = require("uuid");
dotenv.config();
const database = process.env.MONGOLAB_URI;
mongoose
.connect(database, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("User Collection Connected"))
.catch((err) => console.log(err));
const seedUserList = async () => {
let users = [];
for (let i = 0; i < 5; i++) {
const userSeeder = new User({
_id: uuidv4(),
firstname: faker.name.firstName(),
lastname: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email(),
contact_number: faker.phone.number("### ### ####"),
password: faker.internet.password(),
address: faker.address.streetAddress(),
avatar: faker.image.people(1920, 1080, true),
rating: 3,
isVerified: false,
isValidated: false,
});
users.push(userSeeder);
}
const seedUsers = async () => {
await User.deleteMany({});
await User.insertMany(users);
};
seedUsers().then(() => {
console.log("Users Seeded Successfully!");
mongoose.connection.close();
});
};
seedUserList();
module.exports = {
seedUserList,
};
Product Seeder:
const mongoose = require("mongoose");
const Product = require("../models/Product");
const User = require("../models/User");
const dotenv = require("dotenv");
const { faker } = require("#faker-js/faker");
const { v4: uuidv4 } = require("uuid");
dotenv.config();
const database = process.env.MONGOLAB_URI;
mongoose
.connect(database, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("Products Collection Connected"))
.catch((err) => console.log(err));
const seedProductList = async () => {
let products = [];
let ids = [];
let idList = await User.find().select("_id");
idList.map((r) => r.toObject());
for (let i = 0; i < idList.length; i++) {
idList[i] = JSON.stringify(idList[i]);
ids.push(idList[i].substring(8, 44));
}
for (let i = 0; i < 25; i++) {
const productSeeder = new Product({
_id: uuidv4(),
name: faker.commerce.product(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
image: faker.image.image(1920, 1080, true),
category: "Tools",
times_borrowed: faker.datatype.number(),
last_borrowed: faker.date.past(),
product_status: faker.helpers.arrayElement(["Available", "In Use"]),
user_id: faker.helpers.arrayElement(ids),
});
products.push(productSeeder);
}
const seedProducts = async () => {
await Product.deleteMany({});
await Product.insertMany(products);
};
seedProducts().then(() => {
console.log("Products Seeded Successfully!");
mongoose.connection.close();
});
};
seedProductList();
module.exports = {
seedProductList,
};
Database Seeder:
const { seedUserList } = require("./userSeeder");
const { seedProductList } = require("./productSeeder");
const mongoose = require("mongoose");
const seedDatabase = async () => {
seedUserList().then(() => {
console.log("Seeding Users!");
});
await seedProductList().then(() => {
console.log("Seeding Products!");
});
};
seedDatabase().then(() => {
console.log("Database Successfully Seeded!");
mongoose.connection.close();
});
Terminal Output
E:\Projects\Shopping-Platform>node src/seeders/databaseSeeder.js
Seeding Users!
User Collection Connected
Products Collection Connected
Seeding Products!
Database Successfully Seeded!
Products Seeded Successfully!
Users Seeded Successfully!
I've been playing around with the await functionality and wrapping each function with it's own await call so that the ProductSeeder waits for the UserSeeder to complete first before it executes, but so far no luck!

nodejs mongoose CastError (with discordjs)

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

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 send data from react editor to server?

I am trying to create an editor to update my backend data but I am stuck at sending data from client to backend
Here is my following front-end code:
import React, { useState } from "react";
import dynamic from "next/dynamic";
import { convertToRaw, EditorState, getDefaultKeyBinding } from "draft-js";
import draftToHtml from "draftjs-to-html";
const Editor = dynamic(
() => import("react-draft-wysiwyg").then((mod) => mod.Editor),
{ ssr: false }
);
const Missions = ({ teamData, editable }) => {
const { title, mission, teamId } = teamData;
const classes = useStyle();
const [missionContent, setMissionContent] = useState(mission);
const [editing, setEditing] = useState(false);
const [editorState, updateEditorState] = useState(EditorState.createEmpty());
const onEditorStateChange = (editData) => {
updateEditorState(editData);
};
const handleSave = async () => {
const selection = editorState.getSelection();
const key = selection.getAnchorKey();
const content = editorState.getCurrentContent();
const block = content.getBlockForKey(key);
const type = block.getType();
if (type !== "unordered-list-item" && type !== "ordered-list-item") {
if (
editorState.getCurrentContent().getPlainText("").trim().length !== 0
) {
const content = editorState?.getCurrentContent();
let html = await draftToHtml(convertToRaw(content));
await updateEditorState(EditorState.createEmpty(""));
setMissionContent(html.trim());
}
}
setEditing(false);
};
return (
<div className="team-mission-editor-container">
<Editor
wrapperClassName={"mission-editor-wapper"}
toolbarClassName={"mission-editor-toolbar"}
editorClassName={"mission-editor-editor"}
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{...}}
/>
)
Here is my back-end router:
router.put(
"/team/:teamId",
restrictedRoute,
checkData,
catchErrors(checkTeamPermissions),
catchErrors(updateTeamData)
);
and here is my update function from backend:
exports.updateTeamData = async (req, res) => {
// Get userId
const userId = req.session.passport.user.id;
// Get teamId
const publicTeamId = req.params.teamId;
// Fetch private id for team
const teamId = await getTeamId(publicTeamId);
// The user making the request
const userPublicId = req.session.passport.user.publicId;
// The creator of the team
const creatorPublicId = req.body.creator;
// Check who is making the request
if (userPublicId !== creatorPublicId) {
res.status(401).json("msg: You cant update a team you did not create");
}
// Updates
const payload = {
title: req.body.title,
mission: req.body.mission,
inputs: req.body.inputs,
outputs: req.body.outputs,
duration_in_months: req.body.duration_in_months,
status: req.body.status,
mergedTo: teamId,
};
// Update team data
await models.Team.update(payload, {
where: {
id: teamId,
creatorId: userId,
},
});
res.status(200).json("msg: Updated team successfully");
};
How can I send data fromo my editor to backend and update it?
Thank you so much for helping me

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.

Resources