How to Get Started with Mongoose

2014/06/212 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Add Mongoose Dependency to Node Package File
  3. Run NPM Command to Install
  4. Try It Out
  5. Best Practice
  6. Conclusion

Introduction

This article provides information to help you get started with Mongoose. Before you start, you must have NPM and MongoDB installed.

Add Mongoose Dependency to Node Package File

"dependencies": {
    "express": "~4.0.0",
    "mongoose": "3.8.12"
  },

Run NPM Command to Install

npm install mongoose

Try It Out

Try looking at the following examples to write code:

Best Practice

After you have installed Mongoose and tried sample code, you'll wonder what the best practice is for implementation.

You could reference the following article (it has a file to download):

mongoose-connection-best-practice

Conclusion

I think the best approach is to keep all the MongoDB connection logic in one place, which handles connecting to MongoDB, closing the MongoDB connection when Node.js shuts down, error handling for MongoDB, and defining all the collections.

These should all be in one place. Then your Node.js code just requires that file and uses its functions for CRUD operations.