Using CRUD Operations in MongoDB in Node.js Using Mongoose
Take a look at how you can translate JSON data to the Mongoose schema language and then perform CRUD operations.
Join the DZone community and get the full member experience.Join For Free
MongoDB CRUD Operations
Mongoose provides a simple schema-based solution to model your app data. In this post, we will see how we can use it to write basic CRUD operations in Node.js.
First let's write a Mongoose schema for a sample requirement. Example entity is Team, where I want to save:
- Team name
- Team members and their roles
- Who created this team
- CreatedAt and UpdatedAt timestamps
First, let's take a look at how the JSON data will look:
Let's write it in the Mongoose schema language.
The model above is self-explanatory. I have used a timestamp plugin for Mongoose, which will automatically put two fields:
Also, I have used a nested schema in the above example. There is another important thing to see is that I have not defined the
_id field. Mongoose will automatically create this, if I have not mentioned it in my schema. I can also define how I would want my
_id field to be generated.
Add New Record
The above code is pretty simple. You can add more robust checks, and error conditions. You might want to set data in cache.
There are several ways you can update your record, it all depends on your need. Let's see a few simple examples:
Simple Update of A Field
Say, we want to update the team name.
By loading complete object:
By NOT loading complete object
There are bunch of options to do update. You might want to see various options in Mongoose documentation.
Get a Record
The examples above are simple and easy to understand. Let me know if if you have some comments.
You might be also interested in MongoDB backup and Restore.
Published at DZone with permission of Gorav Singal. See the original article here.
Opinions expressed by DZone contributors are their own.