I've read some code that uses the dotenv package to create configurations.
When I read a file that contains PostgreSQL code for Pool, the code looks like this:
const pg = require('pg')
const { Pool } = pg
// This pool was created without completing the pool connection configuration.
const pool = new Pool()
However, I see that this pool configuration is written in the.env file.
#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432
and .env file is called once in main file :
// main file
require('dotenv').config()
const express = require('express')
// below is the server
Why is a pool created without passing any configuration objects as arguments?
How does it work in the background?
I still can't figure this out clearly.
I've tried searching for this behavior, but I haven't found it yet.
When you run
require('dotenv').config()
that sets everything in your .env file to be on process.env.*.
For example, you say PGUSER=username, so now process.env.PGUSER === "username"
pg.Pool seems to go with those environment variables by default
I am learning docker so I was following one of the video it shown that how to connect your js app with mongoDB when it is running in docker containers . Now little variation I did is that it shown to connect mongo on system port 27017 which is default mongo port but the problem is I don't want to connect to my system installed mongo but to the container mongo , so for that purpose I decided to run mongo container on port 3535. When I did so mongo-express successfully got connected to mongo but when I am trying to connect it with my js app(using mongoose ) it is continuously showing errors with authentication error I have checked password is correct , no brackets issue is their , the command I used to turn up my docker containers are
docker run -d -p 3535:27017 --name mongoDB --network databases -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin mongo
and another one for mongo-express is
docker run -d -p 8081:8081 --name mongoExp --network databases -e ME_CONFIG_BASICAUTH_USERNAME=admin -e ME_CONFIG_BASICAUTH_PASSWORD=admin -e ME_CONFIG_MONGODB_SERVER=mongoDB -e ME_CONFIG_MONGODB_AUTH_USERNAME=admin -e ME_CONFIG_MONGODB_AUTH_PASSWORD=admin mongo-express
My node app code looks like
const mongoose = require('mongoose');
const {Humans}= require("./models/humans.js")
mongoose.connect('mongodb://admin:admin#localhost:3535/user', {useNewUrlParser: true, useUnifiedTopology: true }).then(()=>{
console.log("connected to db");
})
let data={
name:"Vaibhav Jain",
mob:"9801",
skills:"coding"
}
const express = require('express')
const app = express();
app.set('view engine', 'ejs');
app.get("/",async(req,res)=>{
// console.log(Humans);
// await Humans.insertMany( );
// await Humans.insertMany({name:"Mobius" , mob:"5908922",skills:"drawing"});
const result = await Humans.find();
res.send(result);
})
app.get("/home",(req,res)=>{
res.render("home", data);
})
app.listen(3000,()=>{
console.log("listening port");
})
Also one thing i would like to mention I have created a user database which have a collection human , this all I created from UI but I wanted to connect it to my app using mongoose , so for that Human which is shown to be imported is actually empty schema (read that from somewhere that you can use existing collections in such a way please correct me on this part also if I am wrong )
Just for refrence current my docker is in this state
You may not have created user for the database user after created it using UI. In your case, you can run this query to create a normal user.
> use user
> db.createUser({user: "user", pwd: "user", roles:["dbOwner"]})
After that, you can connect to user database using this string mongodb://user:user#localhost:3535/user
Check out document db.CreateUser.
I'm running MongoDB Atlas on node express and I got this error when I tested with postman.
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
This is my .env, I'm guessing the problem might be here too, Kindly help:
ATLAS_URI=mongodb+srv://userone:useronepassword1234#cluster0.swye5.mongodb.net/<dbname>?retryWrites=true&w=majority
In my case, I had to go to Atlas, and reset my whitelisted IP to the correct address.
Then I restarted my local server and tried posting again on postman... And it worked!
First replace <dbname> with your actual DB name, if not created,
create one.
Then create collection as required on the Atlas UI itself.
In the Network Access, click on ADD IP ADDRESS and select "allow
access from anywhere".
Rewrite your code this way:
mongoose
.connect(process.env.MONGO_PROD_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true, })
.then(() => console.log("Database connected!"))
.catch(err => console.log(err));
Now your DB should be connected and working fine.
If still not resolved, check this link.
I was facing the same issue. It is resolved. I think you might have not allowed network access to everyone in Atlas: MongoDB. Do it will resolve the issue.
Check your Network Access IP list in MongoDB Cloud.You will only be able to connect to your cluster from the list of IP Addresses
Ensure that your IP Address Setting is Active
Check if you didn't forgot to set password in connection string.
Step 1:
Go to your Atlas account and open your project.
Step 2:
In the left menu, navigate to Network Access section:
Step 3:
Add your IP Address so only you would be able to connect to your cluster. You can also add 0.0.0.0/0 and it will allow access from everywhere.
I also faced the same error. In my case, the error was coming up because useFindAndModify was set to false in mongoose connection
Code with error
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
}, () => {
console.log('connected to database myDb ;)')
})
Working Code
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
}, () => {
console.log('connected to database myDb ;)')
})
Change your MongoDB database-user password. It should be alphanumeric with no special characters. Nothing worked out for me, but, changing the password did.
This error can be caused by typos in user properties. (I was trying to set "Email" instead of what was defined on my user model: "email").
If you are seeing this using Typescript ensure you are importing the connect function from mongoose and use that to connect.
import { connect } from "mongoose";
connect(...).then()
It's kind of late but probably because of this line useCreateIndex: true it's not working. It seems in mongoDB version 5. this is not supported anymore. Rewrite like the answer of manoj_mi5
mongoose
.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true})
.then(() => console.log("Database connected!"))
.catch(err => console.log(err));
to check if there are more errors.
In Mongoose version 6 and above don't require those
{ useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
}
so just delete it.
And if you still see app crashed - waiting for file changes before starting...
just save it one more time and it will work
"error:MongooseError: Operation users.insertOne() buffering timed out after 10000ms"
mongoose.connect(process.env.MONGO_URL, {
useNewURLParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
},6000000)
.then(console.log("connected to server"))
.catch((err) => console.log(err));
add time like 6000000 after options
In Latest version of mongoose.
we don't require this object.
{ useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
}
But if you are dealing with older versions of mongoose then definetly you need it.
Also in your mongodb network address add this address 0.0.0.0/0 in place of your ip address.
in this line of code, ATLAS_URI=mongodb+srv://userone:useronepassword1234#cluster0.swye5.mongodb.net/?retryWrites=true&w=majority
make sure you write actual database name without < > symbols. You have to create your database first in Mongo Atlas.
To solve this, I created a function in index.js, where I asynchronically connecting to my Database and then starting the server, because mongoose doesn't wait for db connection it executes everything on spot, for me that was the problem.
async function start() {
try {
//Database Connect
await mongoose.connect(
process.env.DB_CONNECTION,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
() => {
console.log("Database Connected");
}
);
app.listen(3000, () => {
console.log("Server is running on port 3000 ...");
});
} catch (error) {
console.error(error);
}
}
Double-check some of the things listed below.
Check the username in the database and make sure you have used the same username in the application.
Check the password.
Check the URl of the Database (if any letter is different or changed).
Check the network access if your IP is not present in the IP Access list of the network access section. (Add your IP address if not present there or create add a new IP address).
Add a new IP Address by:
-> click on ADD IP ADDRESS -> click ALLOW ACCESS FROM ANYWHERE -> click confirm.
Also check, if you are on your company's network and added that IP Address to the IP Access list, you might face the same issue, if so, then try switching to your mobile internet or some other than the company's network.
Now, run the application.
Checking the above-all points and making them correct has fixed the issue for me. Hope the same for you. :)
I had this similar issue of recent and what I think gave the error was
require('dotenv').config()
Changed it to this
require('dotenv/config')
or
require('dotenv')
after importing the package, below call the config function
dotenv.config()
I experienced the same issue. But my MongoDB is running locally on my machine. I had forgotten to open the connection before sending my query to the database.
So, I added the code to open and close the connection, and it worked.
try{
await mongoose.connect(uri);
// My mongoose database request code
}
finally{
await mongoose.connection.close();
}
I had the same issue, I removed useCreateIndex: true, and used only:
{
useNewUrlParser: true
}
So I faced the same error but for my case, the reason was because I used the mongoose.createConnection(...) method instead of the mongoose.connect(...) method.
The relevant difference between both of them is that, with mongoose.connect, the created connection is automatically linked with your mongoose models when you do mongoose.model('User', userSchema). However, with mongoose.createConnection, you need to link it with your schema directly like so:
import * as mongoose from 'mongoose'
import { userSchema } from '../path/to/your/schema'
const dbURL = 'mongodb://localhost:27017'
const db = mongoose.createConnection(dbURL, {dbName: 'my-db-name'})
export const User = db.model('User', userSchema)
The important bit is that on the last line, we use the created connection instance db to create our model, rather than using mongoose.model directly.
Keep in mind, this solution is only relevant when you use mongoose.createConnection instead of mongoose.connect
Creating New database user Worked for me.
I turned off my mobile hotspot and back on and it worked.
I am setting up my database connection using a MEVN stack but I am getting the following error;
The `uri` parameter to `openUri()` must be a string, got "undefined"
If I try console log process.env.DATABASE_URL it just returns undefined. What have I done wrong here's my code;
index.js
import dotenv from 'dotenv';
import Express from 'express';
import Mongoose from 'mongoose';
dotenv.config();
const app = Express();
Mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });
app.listen(3000, () => {
// console.log(process.env.DATABASE_URL);
console.log('server started on port 3000');
});
.env
DATABASE_URL="mongodb+srv://reece:<password>#mevn-tutorial-cluster-egjs6.mongodb.net/auth?retryWrites=true&w=majority"
I removed my password for obvious reasons
You have to create a .env file in the root dir of your application.
in the .env file you should have key value separate by equal sign.
As example:
secret=foo
DATABASE_URL=bar:pwd#localhost.com
As the documentation states:
https://www.npmjs.com/package/dotenv
You have not used template literals for mongoose connections.
Try this:
Mongoose.connect(${process.env.DATABASE_URL}, { useNewUrlParser: true });
to get actual .env variable to your Javascript snippet.
I made this mistake, and you shouldn't do it either.
Make sure your.env file is in the root. Check the path of .env before proceeding ahead.
npm install dotenv
require("dotenv").config(); //Keep this at top of your file
In .env file, add
ADMIN_ID="mongoose://******************" //YOUR URL ADDRESS WITH PASSWORD
In app.js file,
mongoose.connect(process.env.ADMIN_ID);
It worked for me.
dotenv.config({ path: "config.env" });
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
})
use path. it'll work
A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.