I'm setting up a bot to work with a MySQL Database.
It worked beforehand and now after I've added the MySQL code it isn't working:
(node:12312) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'query' of undefined
at C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\Bot\events\ready.js:4:20
at Map.forEach (<anonymous>)
at module.exports (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\Bot\events\ready.js:3:25)
at Client.emit (events.js:315:20)
at WebSocketManager.triggerClientReady (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard.<anonymous> (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
at WebSocketShard.onPacket (C:\Users\Admin\Desktop\MuffinMod Data\MuffinMod - Recode\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)
(node:12312) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12312) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
index.js:
require('dotenv').config();
//Database
let connection;
(async () => {
connection = await require('./database/db.js');
})();
//Bot
const Discord = require("discord.js");
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'], restRequestTimeout: 50000 });
const guildSettings = new Map();
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
const DisTube = require('distube');
client.distube = new DisTube(client, { searchSongs: false, emitNewSongOnly: true });
['command', 'event'].forEach(handler =>{
require(`./Bot/handlers/${handler}`)(client, Discord, connection);
});
await client.login(process.env.TOKEN);
ready.js:
module.exports = async(Discord, client, connection) => {
console.log(`Bot online. (${client.user.tag})`);
client.guilds.cache.forEach(guild => {
connection.query(
`SELECT * FROM GuildConfigurable WHERE guildID = ${guild.id}`
).then(result => {
guildSettings.set(guild.id, result[0][0]);
}).catch(err => console.log(err));
});
}
db.js:
const sql = require('mysql2/promise');
module.exports = sql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
})
.then(()=>console.log(`Connected to MySQL Database.`))
.catch(err=>console.error(err));
I think it's an error of the ready.js file being executed before the db.js file can return the connection no idea how to fix it though.
Thanks
As your async method only sets the connection variable once the promise is resolved, it will still be undefined at the point you're using it to set up the event handlers.
You can either keep connection as a promise that is awaited each time it's needed, or move is creation to be in the same async function as it's consumers (as below)
require('dotenv').config();
//Bot
const Discord = require("discord.js");
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'], restRequestTimeout: 50000 });
const guildSettings = new Map();
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
const DisTube = require('distube');
client.distube = new DisTube(client, { searchSongs: false, emitNewSongOnly: true });
(async () => {
const connection = await require('./database/db.js');
['command', 'event'].forEach(handler =>{
require(`./Bot/handlers/${handler}`)(client, Discord, connection);
});
await client.login(process.env.TOKEN);
})();
In db.js you also need to return the connection from the final step of the Promise chain:
const sql = require('mysql2/promise');
module.exports = sql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
})
.then((connection) => {
console.log(`Connected to MySQL Database.`);
return connection;
})
.catch(err=>console.error(err));
Related
I am getting this error ->
(node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:317:13)
at C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ohrid\Desktop\backend2\node_modules\express\lib\router\index.js:275:10)
at logger (C:\Users\ohrid\Desktop\backend2\node_modules\morgan\index.js:144:5)
(node:18420) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18420) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My routes/categories.js:
const { Category } = require('../models/category')
const express = require('express')
const router = express.Router()
router.get(`/`, async (req, res) => {
const categoryList = await Category.find()
if (!categoryList) {
res.status(500).json({ success: false })
}
res.status(200).send(categoryList)
})
router.get('/:id', async (req, res) => {
const category = await Category.findById(req.params.id)
if (!category) {
res.status(500).json({
message: 'The category with the given ID was not found.',
})
}
res.status(200).send(category)
})
router.post('/', async (req, res) => {
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
})
category = await category.save()
if (!category)
return res.status(400).send('the category cannot be created!')
res.send(category)
})
router.put('/:id', async (req, res) => {
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
icon: req.body.icon || category.icon,
color: req.body.color,
},
{ new: true }
)
if (!category)
return res.status(400).send('the category cannot be created!')
res.send(category)
})
router.delete('/:id', (req, res) => {
Category.findByIdAndRemove(req.params.id)
.then((category) => {
if (category) {
return res
.status(200)
.json({
success: true,
message: 'the category is deleted!',
})
} else {
return res
.status(404)
.json({ success: false, message: 'category not found!' })
}
})
.catch((err) => {
return res.status(500).json({ success: false, error: err })
})
})
module.exports = router
My app.js
const express = require('express')
const app = express()
const morgan = require('morgan')
const mongoose = require('mongoose')
const cors = require('cors')
const dotenv = require('dotenv')
require('dotenv/config')
app.use(cors())
app.options('*', cors())
//middleware
app.use(morgan('tiny'))
//Routes
const categoriesRoutes = require('./routes/categories')
const productsRoutes = require('./routes/products')
const usersRoutes = require('./routes/users')
const ordersRoutes = require('./routes/orders')
const api = process.env.API_URL
app.use(`${api}/categories`, categoriesRoutes)
app.use(`${api}/products`, productsRoutes)
app.use(`${api}/users`, usersRoutes)
app.use(`${api}/orders`, ordersRoutes)
mongoose
.connect(
'mongodb+srv://dani:Luka5678#cluster0.23wee.mongodb.net/e-shop?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'e-shop',
}
)
.then(() => {
console.log('Database connection is ready')
})
.catch((err) => {
console.log(err)
})
app.listen(4000, () => {
console.log('server is running on http://localhost:4000')
})
What should I change?
You don't have any error handling layer in your application.
If you use Express v5 and above, route handlers and middleware that return a Promise will catch the errors and will call next(value) automatically.
Otherwise, from asynchronous functions, you must pass them to the next() function, where Express will catch and process them.
That way, you won't get the UnhandledPromiseRejectionWarning.
im trying to implement a basic auth to my api project with knex express and mysql.
i have the following functions
const users = [{ id:1, username:'selia', password:'fullservice'}]
function authenticate({ username, password}) {
const user = users.find(u => u.username === username && u.password === password)
if(user) {
const {password, ...userWithoutPassword} = user
return userWithoutPassword
}
}
module.exports = authenticate
and
const userService = require('../users/user.service.js')
async function basicAuth(req,res,next){
// checando basic auth
if(!req.headers.authorization || req.headers.authorization.indexOf('Basic') === -1) {
return res.status(403).json({ message: 'Header de Autorizacao nao encontrado'})
}
//verificando basuc auth
const base64Credentials = req.headers.authorization.split('')[1]
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii')
const [username, password] = credentials.split(':')
const user = await userService.authenticate({ username, password})
if (!user){
return res.status(403).json({ message: 'Usuario e/ou senha invalidos'})
}
//atribuindo usuario no objeto da requisicao
req.user = user
next();
}
module.exports = basicAuth
and this is my index
const express = require('express')
const routes = require('./routes')
const basicAuth = require('./helpers/basic-auth')
const app = express()
app.use(basicAuth)
app.use(routes)
app.listen(3333, ()=> console.log('Server is running'))
when i run it i get this error
(node:7488) UnhandledPromiseRejectionWarning: TypeError: userService.authenticate is not a function
at basicAuth (/home/matheus/projeto/src/helpers/basic-auth.js:18:30)
at Layer.handle [as handle_request] (/home/matheus/projeto/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/matheus/projeto/node_modules/express/lib/router/index.js:317:13)
at /home/matheus/projeto/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/matheus/projeto/node_modules/express/lib/router/index.js:335:12)
at next (/home/matheus/projeto/node_modules/express/lib/router/index.js:275:10)
at expressInit (/home/matheus/projeto/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/home/matheus/projeto/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/matheus/projeto/node_modules/express/lib/router/index.js:317:13)
at /home/matheus/projeto/node_modules/express/lib/router/index.js:284:7
(node:7488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7488) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
i get this error when i do a get request on insomnia
i belive that this has to do with my async function but i cant figure out how to fix that
sorry for my bad english
Considering how you exported and imported the function, this line is not correct:
const user = await userService.authenticate({ username, password})
It should just be:
const user = await userService({ username, password})
Because your user.service.js module exports a function, NOT an object with an authenticate property.
Trying to query my mySQL database but I can't because i get a TypeError: connection.query is not a function error. Does anyone have any idea why? I don't have any clue as to why this is happening.
database.js
const fs = require('fs'); // node.js file system module
require('dotenv').config(); // stores tokens, keys, passwords and other info
const Discord = require('discord.js'); // links discord.js api to file
const database = require('./database.js');
const client = new Discord.Client(); // creates bot user
let connection;
(async () => {
connection = await require('./database.js');
await client.login(process.env.TOKEN); // bot goes from offline to online
})();
client.once('ready', () => console.info(`[${date.toLocaleString()}] INFO | Ready, logged in as ${client.user.tag} (${client.user.id})\n------------------------`));
client.on('guildCreate', async guild => {
try {
await connection.query(`INSERT INTO guildInfo VALUES('${guild.id}', '${guild.ownerID}')`);
await connection.query(`INSERT INTO guildConfig (guildID) VALUES('${guild.id}')`);
} catch(err) {
console.error(err);
}
});
database.js
require('dotenv').config();
const mysql = require('mysql2/promise');
date = new Date();
mysql.createConnection({
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE
}).then(connection => console.info(`[${date.toLocaleString()}] INFO | Waiting for input/changes to code\n------------------------`)).catch(err => console.error(err));
Error
TypeError: connection.query is not a function
at Client.<anonymous> (C:\Users\Patrick Lawrence\Desktop\Synth\index.js:43:20)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_CREATE] (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\discord.js\src\client\websocket\handlers\GUILD_CREATE.js:33:14)
at WebSocketManager.handlePacket (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\Patrick Lawrence\Desktop\Synth\node_modules\ws\lib\websocket.js:797:20)
at Receiver.emit (events.js:315:20)
Simply you don't export the connection in database.js.
Once created connection, assign it to a variable like const connection and type at bottom of the file module.exports = connection.
Whenever I send a post request with Postman to /api/user/login. It shows user.password is not defined. I'm trying to compare the plain password with the existing hashed password stored in the MongoDB but it's showing a ReferenceError: user is not defined.
Below are the code and the error message with a screenshot. Please let me know where I messed up.
const router = require('express').Router();
const User = require('../model/User');
const bcrypt = require('bcryptjs');
const Joi = require('#hapi/joi');
const registerSchema = Joi.object({
name: Joi.string()
.min(6)
.required(),
email: Joi.string()
.min(6)
.email()
.required(),
password: Joi.string()
.min(6)
.required()
})
const loginSchema = Joi.object({
email:Joi.string()
.required(),
password:Joi.string()
.required()
})
router.post('/register', async(req, res)=>{
const {error} = registerSchema.validate(req.body);
if(error)
return res.status(400).send(error.details[0].message);
// Checking if the user exist in database
const checkExistingEmail = await User.findOne({email: req.body.email});
if(checkExistingEmail) return res.status(400).send('Email already exist');
// Hash passwords
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//Create New Database for user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
try {
const savedUser = await user.save()
res.send({user : user._id});
} catch(err) {
res.status(400).send(err);
}
});
router.post('/login', async(req, res) =>{
const {error} = loginSchema.validate(req.body)
if(error)
return res.status(400).send(error.details[0].message);
// Checking if the user exist in database
const checkExistingEmail = await User.findOne({email: req.body.email});
if(!checkExistingEmail) return res.status(400).send('Email does not exist');
// Check Password
const validPass = await bcrypt.compare(req.body.password, user.password);
if(!validPass) return res.status(400).send('Password does not match');
res.send('Logged In');
});
module.exports = router;
Error is shown here:
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
Server running and listening at port 8081....
Connected to Database...
(node:9380) UnhandledPromiseRejectionWarning: ReferenceError: user is not defined
at D:\tapu\PROJECT WORKS\PROJECT 1.0\Personal Blogging Web Application\Server Side\Login API\routes\auth.js:67:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:9380) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9380) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.
Here is the screenshot with error
You should learn how to read stacktrace first.
UnhandledPromiseRejectionWarning: ReferenceError: user is not defined at D:\tapu\PROJECT WORKS\PROJECT 1.0\Personal Blogging Web Application\Server Side\Login API\routes\auth.js:67:67
There is ReferenceError in your code in file auth.js at line 67.
Instead of chekcExistingEmail you are using user variable.
You can read more about stacktraces here: https://www.digitalocean.com/community/tutorials/js-stack-trace
I am getting this error when i am trying to insert anything into Mongo db. Any help would be appreciated.
const mongoose = require('mongoose');
const dbpath = "mongodb+srv://cluster0-bm7js.mongodb.net/classic";
mongoose.connect(dbpath, {useUnifiedTopology: true , useNewUrlParser: true })
.then(()=> console.log("Now connected to MongoDB!"))
.catch(err=> console.error("Something went wrong", err));
const gameSchema = new mongoose.Schema( {
title: String,
publisher: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
onSale: Boolean,
price: Number
});
const Game = mongoose.model('Game', gameSchema);
async function saveGame() {
const game = new Game( {
title: "Tekken 3",
publisher: "Neogeo",
tags: ["adventure", "action"],
onSale: false,
price: 69.99,
});
const result = await game.save();
console.log(result);
}
saveGame();
This is my code and the error i am getting after running the above code is as,
(node:94819) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [insert] on [classic.games]
at Connection.<anonymous> (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/pool.js:466:61)
at Connection.emit (events.js:198:13)
at processMessage (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/connection.js:533:15)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
(node:94819) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:94819) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Not sure why Mongo db is unable to help me working inside.
Thanks in advance.
const mongoose = require('mongoose');
const dbpath = "mongodb+srv://cluster0-xxxx.mongodb.net/Game";
mongoose.connect(dbpath, {user: 'username', pass: 'password'})
.then(()=> console.log("Now connected to MongoDB!"))
.catch(err=> console.error("Something went wrong", err));
There was an issue with Connection string. All sorted with username and password.