Reputation: 4617
While querying the documents by using collection.find
I started getting following warning in my console
DeprecationWarning: collection.find option [fields] is deprecated and will be removed in a later version
Why am I seeing this and how do I fix this? (Possible alternatives)
EDIT: Query Added
Session
.find({ sessionCode: '18JANMON', completed: false })
.limit(10)
.sort({time: 1})
.select({time: 1, sessionCode: 1});
Mongoose version 5.2.9
Upvotes: 45
Views: 44489
Reputation: 1
The deprecation warnings you're seeing are related to the useNewUrlParser
and useUnifiedTopology
options in your MongoDB connection setup. These options were used in older versions of the MongoDB Node.js driver, but they've been deprecated since MongoDB Node.js driver v4.0.0.
useNewUrlParser
: This option was introduced to handle changes in how MongoDB connection strings are parsed. However, starting from MongoDB driver v4.x, this is the default behaviour, so you no longer need to specify it.
useUnifiedTopology
: This option was used to address issues with server topology discovery and monitoring. Since MongoDB driver v4.x, this is also the default behavior and no longer needs to be explicitly set.
To resolve these deprecation warnings, you can simply remove these options from your Mongoose connection setup. Here’s how your updated code should look:
code:
const mongoose = require("mongoose");
const connectionString = "mongodb+srv://name:[email protected]/?retryWrites=true&w=majority&appName=NodeExpressCluster";
mongoose.connect(connectionString)
.then(() => {
console.log("Connected To The DB");
})
.catch((err) => {
console.log(err);
});
"""
By removing useNewUrlParser
and useUnifiedTopology
, you’ll eliminate the deprecation warnings, as these options no longer have any effect with the current MongoDB driver version you’re using.
Upvotes: 0
Reputation: 41
if depreciation error occurred to you while trying to connect to your mongodb database, if you are storing your connection strings in an environment variables file, like this
//database connection string saved to a env variable
DB='mongodb://127.0.0.1:27017/players'
use the actual ip address instead of the common way of defining it:
DB='mongodb://localhost/players'
Then, when connecting to the database you can use, this code:
//requiring the database driver mongoose
const mongoose = require('mongoose');
//connecting to mongodb
mongoose.connect(process.env.DB)
.then(() => console.log('Connected to mongodb Database...'))
.catch((err) => console.error('Unable to connect to MongoDB...', err));
This definitely, worked for me..am using locally on my machine so if you are using server based database then your database connnection string will not be the same as mine.
Upvotes: 0
Reputation: 11
Am using mongoose version 6.8.0 and this worked for me
//connect mongodb
mongoose.set('strictQuery', false);
mongoose.connect('url',(err,db) => {
if(err){
console.log(`Database not connected : ${err}`)
}else{
console.log('Database connected Successfully')
}
})
Upvotes: 0
Reputation: 771
When we make connection request to connect mongo db we just have to add one more key value pair into that callback function
useCreateIndex:true
inside the function
mongoose.connect(config.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true
}
Upvotes: 1
Reputation: 3279
here
connectionString
is your DB Address
mongoose
.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(
app.listen(port, () => {
console.log(`server started on port ${port}`);
})
)
.catch((err) => console.log(err));
Upvotes: 0
Reputation: 1555
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => {
console.log("DB connected");
})
.catch((err) => console.log(`DB connection Err`, err));
Upvotes: 0
Reputation: 11
You can also use --no-deprecation in CLI to ignore the deprecation warnings.
I was getting this warning- (node:108) [MONGODB DRIVER] Warning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. by using --no-deprecation it worked fine
Check documentation here - https://nodejs.org/dist/latest-v10.x/docs/api/cli.html#cli_no_deprecation
Upvotes: 1
Reputation: 1681
I am currently using "[email protected]" you can get rid of the DeprecationWarning by using this,
Method 1
mongoose.connect("Your DB address", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true // to handle collection.ensureIndex is deprecated
});
Method 2
mongoose.connect("Your DB address", {
useNewUrlParser: true,
useUnifiedTopology: true, // other deprecation warnings
});
mongoose.set("useCreateIndex", true); // to handle collection.ensureIndex is deprecated
Upvotes: 1
Reputation: 2127
Just pass following options while data base connection
for e.g.
const mongoose = require("mongoose");
mongoose.connect("uri",{
"useNewUrlParser": true,
"useUnifiedTopology": true,
"useCreateIndex": true
// other deprecations
},(err)=>{
// connection logging
});
Upvotes: 0
Reputation: 75914
Update:
5.2.10 is released and available for download here.
For more info on the docs you can view page https://mongoosejs.com/docs/deprecations
For more info on the issue and its fix https://github.com/Automattic/mongoose/issues/6880
Original Answer:
Mongoose 5.2.9 version upgraded the native mongodb driver to 3.1.3 in which changes were added to throw warning messages when the deprecated native driver method is called.
fields
option is deprecated and is replaced with projection
option.
You will have to wait for mongoose to make changes at their end to replace the fields option with projection. The fix is scheduled for 5.2.10 release.
For time being you can go back to 5.2.8 which will suppress all deprecation warnings.
npm install [email protected]
For all other deprecated warnings you have to approach them case by case.
You will see other deprecation warnings when you use other collection methods.
DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
DeprecationWarning: collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
All findOne*
mongoose write methods by default use the findAndModify
method which is deprecated in mongodb native driver.
Use mongoose.set('useFindAndModify', false);
to have mongooose call the appropriate findOne*
method on the mongodb native driver.
For remove
and update
replace those calls with delete*
and update*
methods respectively.
For save
replace those calls with insert*
/ update*
methods respectively.
Use mongoose.set('useCreateIndex', true);
to have mongooose call the createIndex
method on the mongodb native driver.
Upvotes: 72
Reputation: 1809
mongoose.connect('mongodb://localhost:27017/tablename',{ useUnifiedTopology: true, useNewUrlParser: true,useCreateIndex: true },()=>{
console.log(
connected db)
});
Upvotes: 1
Reputation: 1820
This worked for me at April, 2020:
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
Upvotes: 1
Reputation: 6121
After upgrading to version 5.2.10. Any of the options below can be use
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {
useCreateIndex: true,
useNewUrlParser: true
})
.then(() => console.log('connecting to database successful'))
.catch(err => console.error('could not connect to mongo DB', err));
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
mongoose.connect('mongodb://localhost/test',{
useNewUrlParser: true
})
.then(() => console.log('connecting to database successful') )
.catch(err => console.error('could not connect to mongo DB', err) );
Upvotes: 5
Reputation: 1434
mongoose.connect('your db url', {
useCreateIndex: true,
useNewUrlParser: true
})
or
mongoose.set('useCreateIndex', true)
mongoose.connect('your db url', { useNewUrlParser: true })
Upvotes: 19
Reputation: 821
You can do a npm install [email protected]
and this will help you get back to an earlier version which will not show any deprecation warnings
Upvotes: 3