Model.findOneAndReplace()

Parameters
  • filter «Object» Replace the first document that matches this filter

  • [replacement] «Object» Replace with this document

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.new=false] «Boolean» By default, findOneAndReplace() returns the document as it was before update was applied. If you set new: true, findOneAndReplace() will instead give you the object after update was applied. To change the default to true, use mongoose.set('returnOriginal', false);.

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.

  • [options.session=null] «ClientSession» The session associated with this query. See transactions docs.

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

  • [options.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.

  • [options.projection=null] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()

  • [callback] «Function»

Returns:
  • «Query»

Issue a MongoDB findOneAndReplace() command.

Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.

Executes the query if callback is passed.

This function triggers the following query middleware.

  • findOneAndReplace()

Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findOneAndReplace(conditions, options, callback) // executes
  2. A.findOneAndReplace(conditions, options) // return Query
  3. A.findOneAndReplace(conditions, callback) // executes
  4. A.findOneAndReplace(conditions) // returns Query
  5. A.findOneAndReplace() // returns Query

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.