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.
Related
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));
homePage.create is not working. i think my problem is here
"mongoose.connect('mongo://localhost:27017/Socialuser', { useNewUrlParser: true, useUnifiedTopology: true });"
App.js file
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
let homePage = require('./models/home');
mongoose.connect('mongo://localhost:27017/Socialuser', { useNewUrlParser: true, useUnifiedTopology: true });
const app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.render('landing.ejs');
});
app.get('/login', (req, res) => {
res.render('loginSignUp.ejs');
});
app.get('/home', (req, res) => {
console.log(homePage);
homePage.create({ name: 'wasim', image: 'https://www.w3schools.com/w3css/img_lights.jpg' }, (err, home) => {
if (err) {
console.log(err);
} else {
console.log('saved');
}
});
});
app.listen(3000, () => {
console.log('server started at port 3000');
});
here is my home.js file.it's the home schema file
const mongoose = require('mongoose');
let homePageSchema = new mongoose.Schema({
name: String,
image: String
// comments: [ String ]
});
module.exports = mongoose.model('Home', homePageSchema);
what is the actual problem i didn't getting what is going on. 'UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string' .....this problem is going
(node:22464) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
at parseConnectionString (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\core\uri_parser.js:547:21)
at connect (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\operations\connect.js:277:3)
at C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\mongo_client.js:222:5
at maybePromise (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\utils.js:662:3)
at MongoClient.connect (C:\Users\wasim\Desktop\social\node_modules\mongodb\lib\mongo_client.js:218:10)
at C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\connection.js:713:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\connection.js:710:19)
at Mongoose.connect (C:\Users\wasim\Desktop\social\node_modules\mongoose\lib\index.js:335:15)
at Object.<anonymous> (C:\Users\wasim\Desktop\social\app.js:6:10)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:22464) 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: 3)
(node:22464) [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.
1) Please use this
mongodb://localhost:27017/Socialuser
Instead of -
mongo://localhost:27017/Socialuser
2) mongoose.connect("mongodb://localhost:27017/[yourDbName]", {
useUnifiedTopology: true,
useNewUrlParser: true
});
In your case yourDbName = Socialuser
Hope this will solve your problem!
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'm new to mongoose, I am trying to set up a get route to '/featured' in my api but am getting the following error '(node:8989) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"'
I am fairly sure I'm just doing something wrong when setting up my router for my blogs. I've tried using .find({'featured': true}), tried .find({featured: true}), tried .find().where('featured', true), tried .find().where('featured').equals(true) and all of them result in the same UnhandledPromiseRejectionWarning: CastError
here is my blog schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title: { type: String, required: true },
article: { type: String, required: true },
published: { type: Date, required: true },
featured: { type: Boolean, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required:true}
});
module.exports = mongoose.model('Blog', BlogSchema);
here is the route I am having trouble with in blogs.js
router.get('/featured', (req, res) =>
{
Blog
.find({'featured': true})
.then(blogs =>
{
if(blogs){
res.status(200).json(blogs)
}
else console.log('blogs not found');
})
.catch(err => console.log(err));
});
here is the error stack trace
(node:16486) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Server is listening on http://localhost:8080
(node:16486) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"
at new CastError (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schema/objectid.js:244:11)
at ObjectId.SchemaType.applySetters (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:948:12)
at ObjectId.SchemaType._castForQuery (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1362:15)
at ObjectId.SchemaType.castForQuery (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1352:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/schematype.js:1331:15)
at cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/cast.js:307:32)
at model.Query.Query.cast (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:4575:12)
at model.Query.Query._castConditions (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:1783:10)
at model.Query.<anonymous> (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/query.js:2038:8)
at model.Query._wrappedThunk [as _findOne] (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/taylour/projects/node200/node200-mongoose-blog-api/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:16486) 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)
I expect to have the "/featured" route return all blogs where the "featured" boolean value is true, but instead I am getting this error no matter what permutations of the query I try for this route
I'm new to mongoose, I am trying to set up a get route to '/featured' in my api but am getting the following error '(node:8989) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "featured" at path "_id" for model "Blog"'
This is saying that you have a document in your mongo collection that looks like {_id: "featured"}. "featured" isn't an ObjectId, so mongoose is erroring when it sees that document because it doesn't know how to handle it.
I am trying to add a PostgreSQL database to my existing nodejs project on heroku. I am having trouble accessing the local version of the database at all, and also having trouble writing to the heroku database.
Here is part of the code that I have tried:
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
I have tried following the instructions here: https://devcenter.heroku.com/articles/heroku-postgresql
but I can't access the local database or do anything to the remote one.
Here is the local error message:
(node:8402) UnhandledPromiseRejectionWarning: error: password authentication failed for user "..."
at Connection.parseE (.../theland/node_modules/pg/lib/connection.js:553:11)
at Connection.parseMessage (.../theland/node_modules/pg/lib/connection.js:378:19)
at TLSSocket. (.../theland/node_modules/pg/lib/connection.js:119:22)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:597:20)
(node:8402) 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:8402) [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 don't know how to create a table on the remote one.
I am running on Linux with
node-v = 8.11.2
npm-v = 6.1.0
pg: ^7.4.3
I am using psql too, no GUI.
Thanks for the help.
EDIT---
Where should I add the authentication? Do I need to take the script off of github if I add the authentication and don't want people to be able to be admins for my database?
password authentication failed for user "..."
Obviously you are not using the right password for the user. The positive news is that there is a server responding your request.
Unhandled promise rejection
There is an error, probably thrown here:
if (err) throw err;
You seem not to catch it somewhere, you only throw it. Try to put it into some try-catch-block, e.g. like
function queryDatabase() {
try {
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
} catch (error) {
// if you need further help, remember to provide this error here.
console.log(error);
}
}