Create your own REST API using node.js and Mongo (Part 3 ) CRUD using Mongoose

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.

1,2,3 CRUD!

C – Create

After you have created the model (Parcel) that is derived from our schema (ParcelSchema) create a parcel object

CREATE.JPG

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.

SAVETODB.JPG

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:

  1. Model.find (conditions, [fields], [options], [callback])
  2. Model.findById (id, [fields], [options], [callback])
  3. Model.findOne (conditions, [fields], [options], [callback])

For this example we will be using the simple find method:

FindAllParcels.JPG

U – Update

Just like the Read operation the Update operation can be used in different ways:

  1. Model.update(condition, update, [options], [callback])
  2. Model.findByIdAndUpdate (id, [update], [options], [callback])
  3. 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.

update

D – Delete

The delete function is similar to the  Update function, here is an example of how we would delete all the parcel documents:

delete

Check out further ways to perform the delete operation here.

Final Thoughts

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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s