Setting up ExpressJS with MongoDB on MERN Project - javascript

So when running Nodemon after setting up an ExpressJS & MongoDB client, I keep getting the
"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."
I'm not really sure where to insert this code into my server.js file.

You'll want to insert it where you're creating your mongo connection.
For example (using mongoose)...
const mongoose = require("mongoose");
const { DATABASE } = process.env; // this a mongodb connection string that varies upon the NODE environment
const options = {
useNewUrlParser: true, // avoids DeprecationWarning: current URL string parser is deprecated
useCreateIndex: true, // avoids DeprecationWarning: collection.ensureIndex is deprecated.
useFindAndModify: false, // avoids DeprecationWarning: collection.findAndModify is deprecated.
useUnifiedTopology: true // avoids DeprecationWarning: current Server Discovery and Monitoring engine is deprecated
};
mongoose.connect(DATABASE, options); // connect to our mongodb database
Here's a Fullstack MERN boilerplate I created and use for my projects, which has an example of how to connect to a local mongo database. You can use it as a reference, if needed.

If you're using mongodb not mongoose, then only need to pass { useUnifiedTopology: true } in your MongoClient.connection options:
MongoClient.connect('mongodb://localhost:27017', { useUnifiedTopology: true })
.then(client => {
// do some stuff
}).catch(error => {
// do some stuff
})
I hope it can help you.

Related

Node.Js MongoParseError URI malformed, cannot be parsed

When I run it on my local computer I don't get any problem, I encounter this error when I deploy it to Heroku. I don't fully understand the reason.
MongoParseError URI malformed, cannot be parsed
I just get this on Heroku. Also, my file on the server.js side is as follows.
const dotenv = require("dotenv");
dotenv.config({ path: "./.env" });
const app = require("./app");
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
console.log(DB);
mongoose
.connect(DB, {
auth: {
user: process.env.MONGO_DB_USER,
password: process.env.MONGO_DB_PASSWORD,
},
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => console.log("DB connection successful!"));
"mongoose": "^5.13.14", "mongoose-intl": "^3.3.0", "dotenv":
"^16.0.3",
My .env file has MongoDB URLs and passwords. That's why I don't share. Works great locally too. but there are problems in deployment.
I had the same issue and it was caused by the fact that on heroku the node version was updated to 19.0.0.
To find out which version of node is being used on heroku, run heroku run 'node -e "console.log(process.versions)"'
The error is caused by mongoose version, maybe you are using an old one.
To solve this, try to update to mongoose 6.7.2 and you should be fine.
If you sure your environment variables are same, it may be related to ip.
Try adding 0.0.0.0/0 IP address in Atlas Network Access. If you already have this IP, then delete and add it again. After that restart all dynos in Heroku. (inside dropdown menu at top right)
check your server dotenv value.
In a cloud environment the .env file may be different.
can you check local process.env and Heroku's process.env?
It seems that there is an error in your mongoDB URI
For now i don't know what your URI is which is .env file but i can suggest you a few things
1- Firstly you need to replace the first two lines of your code with this one
require('dotenv').config();
2- In your .env file you need to create a variable named
MONGODB_URI=mongodb+srv://[username:password#]host[/[database][?options]]
whatever your password and username is just fill in that here in URI
Finally you need to change the connection string and your file should look like this
require('dotenv').config();
const app = require("./app");
mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log("Connection Successfull");
})
.catch((error) => {
console.log("Connection Unsuccessfull");
});

"Error: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms",

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.

How to use 'Node.js 3.0 or later' on mongoose connection?

I am developing a Node JS API but suddently, my MongoDB connection configuration stopped working.
This is how my configuration looks like:
const mongoose = require('mongoose');
try {
mongoose.connect('mongodb+srv://<user>:<password>#hackerrank.jyajn.mongodb.net/<dbname>?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false});
mongoose.Promise = global.Promise;
}
catch(error) {
console.log(error);
}
module.exports = mongoose;
This connection was working until yesterday, but when I tried to run it today it threw the error:
Error: querySrv ENOTFOUND
I saw on this post that
According to MongoDB, SRV is possibly not working due to Mongoose.
So I changed the connection string to the "Node.js 2.2.12 or later" version, as mentioned on the post and it really worked.
My question is, why did this happen? Shouldn't I be able to use the latest connection string, since my node version is v12.17.0?

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

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.

How do I query the DB when the dbPath is not default? MongoDB

Previously I had been connecting to my db like this:
const db = 'mongodb://localhost/dbname';
mongoose.connect(db, {
useMongoClient: true
});
After following along with a tutorial, I decided to change where my logs and db is stored. I changed my connection to:
const db = 'mongodb://localhost:5000';
mongoose.connect(db, {
useMongoClient: true
});
And I created a mongod.conf:
# where to write logging data
systemLog:
destination: file
logAppend: true
path: /Users/matt/mongodb/sampledb/logs/mongod.log
# Where and how to store data
storage:
dbPath: /Users/matt/mongodb/sampledb/data/db
journal:
enabled: true
# network interfaces
net:
port: 5000
bindIp: 127.0.0.1
Now when I "show dbs" from the mongo shell, I am not sure "use" the db to query it. I figure I am missing a step somewhere.
My issue was my that I was using a non-default port. So instead of starting the mongo shell with:
mongo
I needed to start it with:
mongo --port 5000
I also added a name to my db in the connection:
mongoose.connect('mongodb://localhost:5000:/dbname', {
useMongoClient: true
});

Categories