DEV Community

Shameel Uddin
Shameel Uddin

Posted on

10 1 1 2 2

create vs. save in Mongoose (MongoDB) with Node.js

Hello everyone,

I assume you have completed your set up of Mongoose with Node.js/Express.js/Nest.js.

In this blog, we will discuss how the documents can be stored in MongoDB with two different ways and their differences.

Video Explanation

Please find the video explanation below:

Creating Document with .save()

This is one way to create a document:

Image description

Assuming no validation is put in place then whatever "valid" object that you send through, will be stored as a document in MongoDB in the collection.

Creating Document with .create()

This is another way of creating document in MongoDB:

Image description

Difference in .create() and .save()

Official docs suggest this:



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


Enter fullscreen mode Exit fullscreen mode

What it means is that if you call .create(), behind the scenes, it calls .save().

It means, if I am using .create() like this:



const shameel = await User.create({name: 'Shameel', age: 99});


Enter fullscreen mode Exit fullscreen mode

Then, this is hapenning behind the scenes:



const shameel = await new User.create({name: 'Shameel', age: 99}).save();

Enter fullscreen mode Exit fullscreen mode




Schema Validation

.save() bypasses schema validation whereas, .create() adheres to schema validation and throws error.

Creating Multiple Documents

.create() will create documents if you pass an array like this:

Image description

.save() will throw an error if you tend to send an array of objects like that.

Conclusion

You can store documents by the help of create() and save(). If you plan to make sure validators/hooks are called and you can store multiple documents in one go then go for create, else you can go for save.

Happy coding! πŸš€

Follow me for more such content:

πŸš€ Follow on YouTube

πŸš€ Follow on LinkedIn

πŸš€ Follow on GitHub

Top comments (1)

Collapse
 
matthewnichols profile image
Matthew Nichols β€’

Thanks. I am just getting back into Mongoose after some time away and this was helpful.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!