Welcome to part 3 of “Create your own REST API using node.js and Mongo”. In this part of the series we will take a look at how to perform each of the CRUD (Create, Read, Update and Delete) operations on the Mongo database using Mongoose. In Part 2 we connected to our database using Mongoose and saved a parcel item to the database (so you already performed a Create operation, congratulations!). In this post we will run trhough all of the CRUD operations again and we will use Mongoose to interact with our Mongo database just like we did in Part 2.
C – Create
After you have created the model (Parcel) that is derived from our schema (ParcelSchema) create a parcel object
Now the parcel object that has just been created can be saved to our database. If an error occurs during the saving process it will be displayed in the console. Otherwise if the saving of the parcel object to the database was successful it will display “Save successful” and the parcel object in the console.
R – Read
All parcel documents in the database can be read or queried by using the model. The documents can be queried on one of 3 ways:
- Model.find (conditions, [fields], [options], [callback])
- Model.findById (id, [fields], [options], [callback])
- Model.findOne (conditions, [fields], [options], [callback])
For this example we will be using the simple find method:
U – Update
Just like the Read operation the Update operation can be used in different ways:
- Model.update(condition, update, [options], [callback])
- Model.findByIdAndUpdate (id, [update], [options], [callback])
- Model.findOneAndUpdate ([condition], [update], [options], [callback])
We will only be looking at the basic update operation in this post, but you can check out the other methods here.
D – Delete
The delete function is similar to the Update function, here is an example of how we would delete all the parcel documents:
Check out further ways to perform the delete operation here.
And that’s it. You can now create documents, update documents, read documents or delete them from your Mongo database using Mongoose. In the next part, part 4 we will take a look at the express framework for node.js and guide you through the HTTP methods for REST APIs.