Skip to content
Advertisement

What’s the point of using save() in Mongoose?

I’m learning MongoDB and Mongoose, and I’ve watched instructors advise to use the save() function to save the changes made to the database.

But I’m still making changes successfully without using save(). I’ve made two functions to add a document to the database, one with using save() and the second one without using save(), and they all did the same job.

So, what’s the point of using it then?

NOTE: I’ve hided my connect string

My Code:

JavaScript

Terminal output:

JavaScript

Picture of my Database after running my code:

enter image description here

Advertisement

Answer

From the docs:

Shortcut for saving one or more documents to the database. MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.

Looking at what you’ve got, let me point out:

JavaScript

Behind the scenes your code will run like:

JavaScript

What you can do is (this is preferred by most):

JavaScript

The reason is that doing so gives you more control when saving your document. For example, you can pass the person object to any function and save it inside that function instead without requiring the model to wherever that function exists in your codebase.

JavaScript

Doing this allows you to have a better separation of concern. Other than that, both will produce the same behavior and is pretty much a matter of preference. But the current standard in the community goes with the .save() method.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement