Performing Database Operations (Create, Read, Update, Delete) in Node.js with Mongoose and MongoDB Atlas
In this tutorial, we'll guide you through creating a simple student management API using Express, Mongoose, and MongoDB Atlas.
Firstly, we set up our server on port 3000 with an Express app, and a route is created for . The project structure is created using the command , and a new Node.js project is initialized with .
To simplify working with MongoDB, we install Express and Mongoose using the command . Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, making interaction with MongoDB easier with a schema-based approach.
MongoDB Atlas, a fully managed cloud database service by MongoDB, Inc., is used as our database. To set up MongoDB Atlas, we need to create a cluster, create a database user, whitelist our IP address, and obtain a connection URI for the database.
Now, we create a schema named 'StudentSchema' that accepts the fields Id, Name, Roll, Birthday, and Address. With Mongoose models, we have predefined methods for manipulating data for inserting, updating, deleting, and retrieving from the database collection.
To create a new student, we send a POST request to with the new student object using the Mongoose model. To retrieve all records from the Students collection, we send a GET request to .
For more specific operations, we have additional routes. To update a record in the Students collection, we send a PUT request to with the Id of the record to be updated and the new data to be replaced with. To delete a record from the Students collection, we can either use the DELETE request to with the Id of the record to be deleted or use the findByIdAndDelete method by sending a DELETE request to with the Id of the record to be deleted. To retrieve a single record or the first matched document from the Students collection, we send a GET request to with a condition specified.
For testing purposes, we use Postman to send HTTP requests to our Node.js API endpoints. Postman allows us to quickly test our API without the need for a web browser.
MongoDB Atlas, developed by MongoDB, Inc., is a fully managed cloud database service simplifying the deployment, scaling, and management of MongoDB databases in the cloud. Express, on the other hand, is a minimal web framework for Node.js that makes building APIs easy.
With this setup, we have a functional student management API that can be easily expanded and modified to fit our needs. Happy coding!
Read also:
- MRI Scans in Epilepsy Diagnosis: Function and Revealed Findings
- Hematology specialist and anemia treatment: The role of a hematologist in managing anemia conditions
- A Week in Pixelized Realm: The Transformation of the World in Digital Form
- Enhancing the framework or setup for efficient operation and growth