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:
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:
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.
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});
Then, this is hapenning behind the scenes:
const shameel = await new User.create({name: 'Shameel', age: 99}).save();
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:
.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: