"deprecationwarning: collection.findandmodify is deprecated. use findoneandupdate, findoneandreplace or findoneanddelete instead?" Code Answer


you need to set the option in the query usefindandmodify to false, as mentioned in the docs.

(search keyword currently supported options are)

'usefindandmodify': true by default. set to false to make findoneandupdate() and findoneandremove() use native findoneandupdate() rather than findandmodify().

and if you see the definition file of mongoose, where mentioned that it calls findandmodify update command.

  * issues a mongodb findandmodify update command.
  * finds a matching document, updates it according to the update arg, 
    passing any options,
  * and returns the found document (if any) to the callback. the query 
    executes immediately
  * if callback is passed else a query object is returned.
 findoneandupdate(): documentquery<t | null, t>;

recently updated in the mongoose docs (click here) for these deprecation where mentioned:

mongoose's findoneandupdate() long pre-dates the mongodb driver's findoneandupdate() function, so it uses the mongodb driver's findandmodify() function instead.

there are three ways or more by which you can avoid the use of findandmodify:

  1. at global level: set the option to false.
// make mongoose use `findoneandupdate()`. note that this option is `true`
// by default, you need to set it to false.
mongoose.set('usefindandmodify', false);
  1. at connection level: we can configure using the connection options:
    mongoose.connect(uri, { usefindandmodify: false });
  1. at query level:
   await modelname.findoneandupdate({matchquery},
   {$set: updatedata}, {usefindandmodify: false});

By Mehrad Sadegh on March 16 2022

Answers related to “deprecationwarning: collection.findandmodify is deprecated. use findoneandupdate, findoneandreplace or findoneanddelete instead?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.