Update The Documents Using Mongoose

Pranay Chauhan
Last Updated: May 13, 2022

Introduction

When we work with the backend development of our application.

You must have noticed that we create a database to store the relevant data to be displayed by our application in the frontend.

Do you think this data is always constant?

Obviously no; we are always required to update the data that has already been present in the database.

This article will tell us about the different ways to update the documents using the mongoose library.

Let us first learn the basics about mongoose.

Mongoose

Mongoose is Object Data Modelling (ODM) library for mongoDB. Mongoose handles the relationship between data, and provides the schema validation, and it is used to translate between the objects and the representation of those objects in MongoDB.

Mongoose has mainly four different ways to update a document. Here is a list of these methods:

  • Document.save()
  • Model.updateOne() and updateMany()
  • Document.updateOne()
  • Model.findOneAndUpdate()

Let us learn more about each of the methods in detail.

Using save()

Below is an example of using save() to update John Smith's title.

const schema = new mongoose.Schema({ name: String, title: String });
const CharacterModel = mongoose.model('Character', schema);

const doc = await CharacterModel.create({
 name: 'John Smith',
 title: `Lord Commander of the Night's Watch`
});

doc.title = 'King in the North';
await doc.save();

In the above code, we first use the save() method. save() method is dependent on a document, which simple implies that there must exist a document at the first place. So for that we need to first use create() or find() method to create or fetch a document respectively.

Secondly, The documents in the mongoose have track changing. Internally, when we call the doc.save() method, mongoose will know that we save the title, and then it will transform into the updateOne({$set:{title}}).

Using Model.updateOne() and Model.updateMany()

By using the Model.updateOne() and Model.updateMany() function, we can update the document even without loading it from the database. 

In the below code example, The document with the name=’John Smith’ is not in the memory of Node.js process, when we call the function updateOne().

// Update the document using `updateOne()`
await CharacterModel.updateOne({ name: 'John Smith' }, {
 title: 'King in the North'
});

const doc = await CharacterModel.findOne();
doc.title; // "King in the North"

The updateMany() function is much similar to the updateOne() function. The difference between these two functions is that updateOne() will update at most one document, whereas updateMany() will update every document that matches the filter.

You should use save() rather than updateOne() and updateMany() functions where ever it is possible. Also, Model.updateOne() and Model.updateMany() functions also have some advantages:

  • updateOne() is atomic. If we load a document using find() function then it can change before we use save() function on it.
  • updateOne() doesn't require us to load the document into memory, which can give us better performance if our documents are huge.

Using Document.updateOne()

The Document.updateOne() function is syntactically much better compared to the Model.updateOne() function. If we already have a document in the memory, then the doc.updateOne() will internally structure a Model.updateOne() function call.

// Load the document
const doc = await CharacterModel.findOne({ name: 'John Smith' });

// Update the document using `Document#updateOne()`
// Equivalent to `CharacterModel.updateOne()
const update = { title: 'King in the North' };
await doc.updateOne(update);

const updatedDoc = await CharacterModel.findOne({ name: 'John Smith' });
updatedDoc.title; // "King in the North"

Document.updateOne() is rarely useful in general. We can better use the save() function and using Model.updateOne() for the cases when save() is not very flexible.

Using Model.findOneAndUpdate()

The Model.findOneAndUpdate() function and its variation Model.findByIdAndUpdate() are similar in their behaviour with the updateOne() function. 

These functions atomically update the first document which matches the first parameter filter.

These functions also give the updated document in return, unlike the updateOne().

const doc = await CharacterModel.findOneAndUpdate(
 { name: 'John Smith' },
 { title: 'King in the North' },
 // If `new` isn't true, `findOneAndUpdate()` will return the
 // document as it was before it was updated.
 { new: true }
);

doc.title; // "King in the North"

Which is best?

As shown below in the image, We see that Document.save() has the highest number of ticks in its row. It has the functionality of Document in memory. It also returns the updated doc, and it is the only function that allows tracking of the changes done in the document. 

Below is the overview of features available in each of the four different ways.

Frequently Asked Questions (FAQs)

  1. What is mongoose?
    Mongoose is Object Data Modelling (ODM) library for mongoDB. Mongoose handles the relationship between data, and provides the schema validation, and it is used to translate between the objects and the representation of those objects in MongoDB.
     
  2. Which is the best method in general for updating the document?
    The best method for updating the document is Document.save().
     
  3. What are the two methods used for atomic update in document?The two methods used for atomic update in document is Model.updateOne() and Model.findOneAndUpdate().

Key Takeaways

We learned about the concept of destructuring in javascript. This is an interesting technique of destructuring data structures in javascript that allows us to use individual elements of arrays and objects. This article also explained the implementation of array destructuring and object destructuring.

You can also expand your knowledge by referring to these articles on Javascript.

For more information about the react framework for frontend development, get into the entire Backend web development course.

Happy Learning!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think