I tried to run the server in my MERN project but it gives me a MongoParseError.
My code is,
const mongoose = require("mongoose");
module.exports = async() => {
try {
const connectionParams = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
};
await mongoose.connect("mongodb://localhost/todo-app", connectionParams);
console.log("Connected to database.");
} catch (error) {
console.log("Could not able to connect to database.", error);
}
};
And the error message was,
Listening on port ${port}...
Could not able to connect to database. MongoParseError: option usecreateindex is not supported
How to fix this?
This error occurs due to the Deprecation Warning Options.
To avoid this:
Remove useCreateIndex: true,
Now run the server.
You can also try:
Remove entire const connectionParams = {....};
Remove the comma and connectionParams parameter.
Now run the server.
Your final code should look like:
const mongoose = require("mongoose");
module.exports = async() => {
try {
await mongoose.connect("mongodb://localhost/todo-app");
console.log("Connected to database.");
} catch (error) {
console.log("Could not able to connect to database.", error);
}
};
Because useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. So please remove these options from your code.
for more clarifications refer here
Related
This is frustrating. No clues why I got this error while documentation still has it. Please help!
My code to connect MongoDB with mongoose.
const mongoose = require('mongoose');
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
} catch (err) {
console.log(`Error: ${err.message}`.red);
process.exit(1);
}
}
module.exports = connectDB;
Error: option usecreateindex is not supported
Documentation says useCreateIndex is the updated method.
https://mongoosejs.com/docs/deprecations.html#
to me, I just remove useCreateIndex
First, in your project root dir in npm i mongoose command to install Mongoose, then use this code to connect with MongoDB And create a new database.
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api', {
useNewUrlParser: true,
useCreateIndex: true
})
useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.
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.
I am trying to connect to a cluster created in Mongodb Atlas using mongoose in node js and I am facing below issues when doing so.
When I use the connection string that is given in the Mongo db atlasmongodb+srv://lm_dev_app:<password>#lmdev-q5biw.mongodb.net/test?retryWrites=true&w=majorityI get below error
{ Error: queryTxt EBADNAME lmdev-q5biw.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'lmdev-q5biw.mongodb.net'}
I cannot use this connection string in Mongodb Compass as well as I am getting the same error there.
If I try to connect using mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test i get below error
MongooseServerSelectionError: connection to 54.66.221.230:27017 closed
However I am able to connect to each node using Mongodb Compass which eliminates the possibility of my ipaddress not being whitelisted.
Here is the sample code that I am using
const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
replicaSet: "LMDEV"
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
Any thoughts on what is happening here.
There are couple of things that I need to highlight here.
The default connection string that is shown in Mongodb Atlas seems to be wrong. It shows you mongodb+srv://<username>:<password>#<cluster_url>/test?retryWrites=true&w=majority. But I used mongodb://<username>:<password>#<node_url>:27017/ to make it work. You can also use mongodb://<username>:<password>#<node_url>:27017/admin.
Pass ssl:true in the options that we are passing.
Finally one of the 3 options can be used to connect to the database.
a. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
b. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
c. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/admin", {
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
EDIT 1:
After having a chat with Atlas support team I was told that issue in point 1 is due to DNS resolution issue with my service provider. So i have changed my DNS settings to point to a public DNS server.
After trying different connection strings for several hours, I finally just copy/pasted the connection string from MongoDB Compass and it works! (first connect, then edit the connection string as it will change)
It looks like this:
mongodb+srv://username:password#fra-atlas-shard.abcde.mongodb.net/test?authSource=admin&replicaSet=atlas-abcde-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true
I am using mongoose.connect() method but it couldn't created a DB ,i did even insert some documents in
db by using insertMany() but it neither giving me any error nor creating a DB as when i checked my mongo Shell todolistDB is not created .
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/todolistDB', {
useNewUrlParser: true,
useUnifiedTopology: true },
function (err) {
if (err) {
console.log(err);
} else {console.log('server is connected');}})
const itemsSchema = mongoose.Schema({name: {type: String,required: true }})
const Item = mongoose.model('Item', itemsSchema)
const item1 = new Item({name: 'Welcome to your todo list!'})
const item2 = new Item({name: 'Hit + button to add new item'})
const item3 = new Item({name: '<-- click to delete a item!'})
const defaultItems = [item1, item2, item3]
app.get('/', function (req, res) {
Item.find({}, function (err, result) {
if (defaultItems.length===0) {
**even after insertmany method todolistDB is not created**
Item.insertMany(defaultItems, function (err) {
if (err) {
console.log(err);
} else {
console.log('new record inserted successfully!');}});
} else {
res.render('list', {listTitle: 'today',latestItems: result}) }
** when I used insertMany outside app.get() method then all records was inserted, I just started learning mongoDB sorry in advanced if it was a silly mistake **
detailed answer would be appreciated!
Consider the following three lines of your code:
[1] const defaultItems = [item1, item2, item3]
[2] Item.find({}, function (err, result) {
[3] if (defaultItems.length===0) {
In [2] you are doing a query, presumably it returns no results and you get to [3]. However in [3] you are referencing the fixed set defined in [1] which is of length 3. Thus the if statement in [3] is never entered.
The code is pretty fine.
mongoose.connect() call is fine. Since you are writing it in Promise form, issue is Unhandled Promise Rejection for connection failure.
Console the error, the error message would give us better glimpse.
Coming to the error possibilities, it is likely to happen if you use middleware handler app.use or router.use.
Please console the error, drop down the error message. So that I can help you further.
You Can Follow This Code
mongoose.connect('mongodb://localhost:27017/todolistDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
mongoose.connection.on("connected", () => {
console.log("Mongodb connected")
})
mongoose.connection.on("error", errMsg => {
console.log("Error connecting database. Msg: " + errMsg)
})
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.