I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error
See my code below:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
connectDB().catch(err => console.log(err));
async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
})
.then(() => console.log("DB Connection Success"))
.catch((err) => console.log(err));
}
app.listen(8800, () => {
console.log("Backend Server is running");
});
Same problem here... solved with encodeURIComponent on the part of the string that had the password
const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "#cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";
Maybe provide username and password as option:
const options = {
user: <username>,
pass: <password>,
authSource: "admin",
useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);
I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".
Related
Tried to connect To mongodb, it says connection not found. can someone point out what error I have made in code, is there any problem in db connect URI
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db =
"mongodb+srv://<sumit>:<sumit>#bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
console.log(db);
mongoose
.connect(db)
.then(() => {
console.log("connection successful");
})
.catch((err) => console.log(err));
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
This is a snippet from my own application it works there
mongoose.connect(dbUrl).then((dbo)=>{
console.log("DB connected")
},(err)=>{
console.log("error")
});
I have connected like this your then is missing a variable tell me if this dosnt work
Finally found a solution.
Thanks for the help #ahmed ali.
In db uri, username and password should be written without angular brackets and replace the first database with your database name created.
Write down the username and password example:
monggoose.connect('mongodb+srv://name:password#cluster0.cjjucgj.mongodb.net/?retryWrites=true&w=majority')
I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.
Hi i'am trying to connect a database to server.js with Knex.js i have tried to add user as postgresql and i tried also to add host as localhost but that didn't work an i always get
Below is when i list all the databases!
Failed to load resource: the server responded with a status of 400 (Bad Request)
Below is a snapshot of my error when i tries to register me!
Below is my register.js that should help with the reigistering to the database!
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister: handleRegister
};
Here is my server.js file below!
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : 'localhost',
user : 'postgres',
database : 'smartbrain1'
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
And here is my databases that i have created in postgreSQL in the terminal as a snapshot!
You should start by just trying to write standalone node app, that connects pg and runs a query. Then You can start integrating with other parts of your app when you know that connecting DB works as expected. Now the question has way too much irrelevant information.
First try to connect your SQL server from shell without using UNIX socket, but with TCP:
psql postgres://postgres#localhost/smartbrain1
If that fails, it probably means that your database is configured so that it does not allow any external TCP connections.
To allow access from localhost to postgres this should do it in pg_hba.conf by setting
host all all 127.0.0.1/32 trust
Also you may need to add password for your postgres user and try connecting with password enabled:
psql postgres://postgres:<password>#localhost/smartbrain1
When connecting from command line works you can try something like this in knex config:
const db = knex({
client: 'pg',
connection: 'postgres://postgres:<password>#localhost/smartbrain1'
});
Some more info for debugging this is found here Knex:Error Pool2 - error: password authentication failed for user and probably in tens of other generic postgres database connection problem questions.
I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,
I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.
I am trying to connect to mongoDB atlas.But can't do it anyway.I have tried all options that found on the stackoverflow
My server.js is like as below
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
/*
-------------- Mongo db connection -----------
*/
const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://tintindenmark#gmail.com:*********#cluster0-f9upb.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true });
mongoose.connection
.once('open', () => console.log('Good to go!'))
.on('error', (error) => {
console.warn('Warning', error);
});
/*
------------------------ Mongo db connection ends ------------------------
*/
app.prepare().then(() => {
const server = express()
server.get('/about', (req, res) => {
return app.render(req, res, '/about', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
but i cant do it anyway.I have whitelisted IP addresses from atlast clusters.
Also tried without mongodb+srv.It didnt worked also
Always i am getting this errorMongoNetworkError: failed to connect to server [cluster0-shard-00-01-f9upb.mongodb.net:27017] on first connect [MongoError: Authentication failed.]
I also tried mongodb+srv://tintindenmark#gmail.com:musassmc42#cluster0-f9upb.mongodb.net:27017/test but it also didn't work
So what else i can do to connect??
My mongoose version is : 5.6.6
tintindenmark#gmail.com:musassmc42, this username:password is of your atlas account and not your database.
Created a new user and password for you. Try:
mongodb+srv://testuser:testpassword#cluster0-f9upb.mongodb.net:27017/test
And change all passwords.