node

How to use findOneAndUpdate in mongoose


In this article, you will learn about how to use Mongoose findOneAndUpdate

In Mongoose there are many effective methods for updating data. Each method is designed for a single purpose but they work differently. One of these methods is findOneAndUpdate(). Mongoose’s findOneAndUpdate() function finds the first document that matches a given filter, then applies an update, and finally returns the document.

Getting started with Mongoose’s findOneAndUpdate() you need at least two parameters to call findOneAndUpdate(). One is a filter and another is an update. Follow the code example below:

const Student = mongoose.model('Student', Schema({
  name: String,
  age : String
}));

await Character.create({ name: 'Alex' });

// By default, `findOneAndUpdate()` returns the document as
// it was **before** MongoDB applied the update.
const filter = { name: 'Alex' };
const update = { age: '19' };
let doc = await Student.findOneAndUpdate(filter, update);
doc.name; // 'Luke Skywalker'
doc.age; // undefined

// But the document is updated in the database:
doc = await Student.findOne(filter);
doc.age; // '19'

Here, MongoDB finds the first document that matches the filter and applies update. By default, findOneAndUpdate() returns the document as it was before MongoDB applied update.

If you want to return the document as it was after MongoDB applied the given update, you have to set the new option to true. Such as :

/* If you set the `new` option to `true`, Mongoose will
 return the document with the update applied. */
const filter = { name: 'Alex' };
const update = { age: '19' };
const opts = { new: true };

let doc = await Student.findOneAndUpdate(filter, update, opts);
doc.name; // 'Alex'
doc.age; // '19'

You can use several other options for findOneAndUpdate(). For example, The upsert option is one of them. Follow the example below:

const filter = { name: 'Alex' };
const update = { age: 19 };

await Student.countDocuments(filter);// 0
let doc = await Student.findOneAndUpdate(filter, update, {
  new: true,
  upsert: true// Make this update into an upsert
});
doc.name;// 'Alex'
doc.age;// '19'

Mongoose provides a dedicated middleware for findOneAndUpdate(). If you call findOneAndUpdate() it will not eject the findOne, updateOne, or save middleware. Instead, It will eject findOneAndUpdate middleware. For example:

const schema = Schema({
  name: String,
  age: String
});
schema.pre('findOneAndUpdate', function middleware() {
  this.getFilter(); // { name: 'Alex' }
  this.getUpdate(); // { age: '19' }
});
const Student = mongoose.model('Student', schema);

const filter = { name: 'Alex' };
const update = { rank: '19' };
// Mongoose calls the `middleware()` function above
await Student.findOneAndUpdate(filter, update, opts);

This is all about mongoose findOneAndUpdate and you can get an overview from it.


Share on social media

//