admin管理员组

文章数量:1136423

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

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

Share Improve this question edited Dec 3, 2020 at 3:34 s7vr 75.9k11 gold badges117 silver badges135 bronze badges asked Aug 19, 2018 at 10:14 It worked yesterday.It worked yesterday. 4,61711 gold badges49 silver badges83 bronze badges 7
  • Did you try to use collection.find(query).limit(1).project({name:1})? – Daniele Tassone Commented Aug 19, 2018 at 12:27
  • Hi @DanieleTassone whenever i use find() this warning appears – It worked yesterday. Commented Aug 19, 2018 at 12:32
  • Could you post your full query – Ashh Commented Aug 19, 2018 at 12:50
  • 1 the native mongodb driver is something that Mongoose internally use to deal with MongoDB. If Mongoose do not respect some new "rules" then a warning is returned back. With native-driver you will receive this warning if you use "fields option" instead of cursor function for example. Take a look here: github.com/Automattic/mongoose/issues/6667 – Daniele Tassone Commented Aug 19, 2018 at 13:49
  • 1 There is an issue on github is opened... So till it gets resolved you can use mongoose version 5.2.8 – Ashh Commented Aug 20, 2018 at 5:59
 |  Show 2 more comments

15 Answers 15

Reset to default 72

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.

mongoose.connect('your db url', {
  useCreateIndex: true,
  useNewUrlParser: true
})

or

mongoose.set('useCreateIndex', true)
mongoose.connect('your db url', { useNewUrlParser: true })

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));


or

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) );

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

This worked for me at April, 2020:

mongoose.connect(process.env.DATABASE_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
})

mongoose.connect('mongodb://localhost:27017/tablename',{ useUnifiedTopology: true, useNewUrlParser: true,useCreateIndex: true },()=>{ console.log(connected db) });

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

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

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
}

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

});

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));

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));

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')
    }
})

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.

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.

What’s the Issue?

  • 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.

What Should You Do?

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.

本文标签: javascriptMongoDB mongoose Deprecation WarningStack Overflow